From 0b8be6a3a8e4fce0030c58d7300f5eb124a80137 Mon Sep 17 00:00:00 2001 From: "J. Cheyo Jimenez" Date: Mon, 18 Jul 2016 22:33:21 -0700 Subject: [PATCH] Swift3branch (#160) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [wip] remove swift 3 directive * [wip] mechanical transition with code migrator * Swift 3 preview 1 changes * travis xcode8 update * travis update OS X 10.12 * updated documentation to swift 3 and Xcode 8 * Removed "Foundation not needed" comment Unlike Objc, swift doesn’t need foundation for most simple operations. I was planning to remove the foundation requirement but now swift 3.0 will provide a Swift version of foundation. https://github.com/apple/swift-corelibs-foundation * ran swiftLink locally with autocorrect - This next step is to turn this on on Travis CI to warn on commit * travis update with swiftlint * update travis * added swiftlint rules yml * update read me with contribution guides closes https://github.com/exercism/xswift/issues/66 * update swiftLint rules * force swift3 for XCTest classes by using compiler directive. By wrapping the import to only import when swift 3 is present I am hoping to impress to users that swift 3 is required. Plus this would make it easy to go back and keep requiring a certain a version in the future. * BinarySearchTree using indirect enums closes https://github.com/exercism/xswift/issues/152 reference: https://airspeedvelocity.net/2015/07/22/a-persistent-tree-using-indirect -enums-in-swift/ * update swiftlint format requirement update swift lint doc and script in Xcode project `swiftlint autocorrect --format` * operator_whitespace removal * removed leading white space * mid triple new lines clean up * closes #10 --- .swiftlint.yml | 10 + .travis.yml | 8 +- README.md | 4 + docs/INSTALLATION.md | 4 +- docs/LEARNING.md | 4 +- exercises/accumulate/AccumulateExample.swift | 6 +- exercises/accumulate/AccumulateTest.swift | 95 ++- exercises/acronym/AcronymExample.swift | 84 ++- exercises/acronym/AcronymTest.swift | 35 +- exercises/allergies/AllergiesExample.swift | 28 +- exercises/allergies/AllergiesTest.swift | 65 +-- exercises/anagram/AnagramExample.swift | 26 +- exercises/anagram/AnagramTest.swift | 47 +- exercises/atbash-cipher/AtbashExample.swift | 44 +- exercises/atbash-cipher/AtbashTest.swift | 27 +- .../BinarySearchTreeExample.swift | 101 ++-- .../BinarySearchTreeTest.swift | 24 +- .../binary-search/BinarySearchExample.swift | 47 +- .../binary-search/BinarySearchTest.swift | 24 +- exercises/binary/BinaryExample.swift | 38 +- exercises/binary/BinaryTest.swift | 30 +- exercises/bob/BobExample.swift | 61 +- exercises/bob/BobTest.swift | 42 +- exercises/clock/ClockExample.swift | 26 +- exercises/clock/ClockTest.swift | 108 ++-- .../crypto-square/CryptoSquareExample.swift | 121 ++-- .../crypto-square/CryptoSquareTest.swift | 36 +- exercises/custom-set/CustomSetExample.swift | 103 ++-- exercises/custom-set/CustomSetTest.swift | 97 ++-- .../DifferenceOfSquaresExample.swift | 30 +- .../DifferenceOfSquaresTest.swift | 29 +- exercises/dominoes/DominoesExample.swift | 136 ++--- exercises/dominoes/DominoesTest.swift | 28 +- exercises/etl/EtlExample.swift | 11 +- exercises/etl/EtlTest.swift | 46 +- exercises/food-chain/FoodChainExample.swift | 26 +- exercises/food-chain/FoodChainTest.swift | 156 ++--- exercises/gigasecond/GigasecondExample.swift | 80 ++- exercises/gigasecond/GigasecondTest.swift | 25 +- .../grade-school/GradeSchoolExample.swift | 20 +- exercises/grade-school/GradeSchoolTest.swift | 76 +-- exercises/grains/GrainsExample.swift | 19 +- exercises/grains/GrainsTest.swift | 34 +- exercises/hamming/HammingExample.swift | 18 +- exercises/hamming/HammingTest.swift | 26 +- exercises/hello-world/helloWorld.swift | 4 +- .../helloWorld.xcodeproj/project.pbxproj | 4 +- exercises/hello-world/helloWorldExample.swift | 6 +- .../helloWorldTest/helloWorldTest.swift | 26 +- .../hexadecimal/HexadecimalExample.swift | 32 +- exercises/hexadecimal/HexadecimalTest.swift | 30 +- exercises/house/HouseExample.swift | 25 +- exercises/house/HouseTest.swift | 186 +++--- .../KindergartenGardenExample.swift | 40 +- .../KindergartenGardenTest.swift | 54 +- .../LargestSeriesProductExample.swift | 42 +- .../LargestSeriesProductTest.swift | 66 +-- exercises/leap/LeapExample.swift | 12 +- exercises/leap/LeapTest.swift | 42 +- exercises/linked-list/LinkedListExample.swift | 32 +- exercises/linked-list/LinkedListTest.swift | 20 +- exercises/luhn/LuhnExample.swift | 78 +-- exercises/luhn/LuhnTest.swift | 28 +- exercises/matrix/MatrixExample.swift | 30 +- exercises/matrix/MatrixTest.swift | 20 +- exercises/meetup/MeetupExample.swift | 153 +++-- exercises/meetup/MeetupTest.swift | 34 +- .../minesweeper/MinesweeperExample.swift | 110 ++-- exercises/minesweeper/MinesweeperTest.swift | 62 +- exercises/nth-prime/NthPrimeExample.swift | 18 +- exercises/nth-prime/NthPrimeTest.swift | 18 +- .../NucleotideCountExample.swift | 39 +- .../NucleotideCountTest.swift | 29 +- exercises/ocr-numbers/OcrNumbersExample.swift | 108 ++-- exercises/ocr-numbers/OcrNumbersTest.swift | 170 +++--- exercises/octal/OctalExample.swift | 36 +- exercises/octal/OctalTest.swift | 39 +- .../PalindromeProductsExample.swift | 67 +-- .../PalindromeProductsTest.swift | 16 +- .../PascalsTriangleExample.swift | 20 +- .../PascalsTriangleTest.swift | 20 +- .../PerfectNumbersExample.swift | 22 +- .../perfect-numbers/PerfectNumbersTest.swift | 31 +- .../phone-number/PhoneNumberExample.swift | 23 +- exercises/phone-number/PhoneNumberTest.swift | 27 +- exercises/pig-latin/PigLatinExample.swift | 86 ++- exercises/pig-latin/PigLatinTest.swift | 43 +- exercises/poker/PokerExample.swift | 256 ++++---- exercises/poker/PokerTest.swift | 546 +++++++++--------- .../prime-factors/PrimeFactorsExample.swift | 35 +- .../prime-factors/PrimeFactorsTest.swift | 36 +- .../PythagoreanTripletExample.swift | 36 +- .../PythagoreanTripletTest.swift | 29 +- .../queen-attack/QueenAttackExample.swift | 73 +-- exercises/queen-attack/QueenAttackTest.swift | 100 ++-- exercises/raindrops/RaindropsExample.swift | 35 +- exercises/raindrops/RaindropsTest.swift | 42 +- .../RnaTranscriptionExample.swift | 22 +- .../RnaTranscriptionTest.swift | 17 +- exercises/robot-name/RobotNameExample.swift | 12 +- exercises/robot-name/RobotNameTest.swift | 12 +- .../RobotSimulatorExample.swift | 77 ++- .../robot-simulator/RobotSimulatorTest.swift | 134 ++--- .../roman-numerals/RomanNumeralsExample.swift | 33 +- .../roman-numerals/RomanNumeralsTest.swift | 44 +- .../saddle-points/SaddlePointsExample.swift | 40 +- .../saddle-points/SaddlePointsTest.swift | 28 +- .../scrabble-score/ScrabbleScoreExample.swift | 76 +-- .../scrabble-score/ScrabbleScoreTest.swift | 26 +- .../SecretHandshakeExample.swift | 37 +- .../SecretHandshakeTest.swift | 27 +- exercises/series/SeriesExample.swift | 27 +- exercises/series/SeriesTest.swift | 41 +- exercises/sieve/SieveExample.swift | 46 +- exercises/sieve/SieveTest.swift | 13 +- .../simple-cipher/SimpleCipherExample.swift | 92 ++- .../simple-cipher/SimpleCipherTest.swift | 17 +- .../SimpleLinkedListExample.swift | 52 +- .../SimpleLinkedListTest.swift | 48 +- exercises/space-age/SpaceAgeExample.swift | 33 +- exercises/space-age/SpaceAgeTest.swift | 29 +- exercises/strain/StrainExample.swift | 22 +- exercises/strain/StrainTest.swift | 51 +- .../SumOfMultiplesExample.swift | 20 +- .../sum-of-multiples/SumOfMultiplesTest.swift | 24 +- exercises/tournament/TournamentExample.swift | 234 ++++---- exercises/tournament/TournamentTest.swift | 59 +- exercises/triangle/TriangleExample.swift | 66 +-- exercises/triangle/TriangleTest.swift | 72 +-- exercises/trinary/TrinaryExample.swift | 42 +- exercises/trinary/TrinaryTest.swift | 30 +- exercises/twelve-days/TwelveDaysExample.swift | 27 +- exercises/twelve-days/TwelveDaysTest.swift | 43 +- exercises/word-count/WordCountExample.swift | 40 +- exercises/word-count/WordCountTest.swift | 35 +- exercises/wordy/WordyExample.swift | 129 ++--- exercises/wordy/WordyTest.swift | 41 +- xcodeProject/xSwift.xcodeproj/project.pbxproj | 204 ++++--- 138 files changed, 3335 insertions(+), 4028 deletions(-) create mode 100644 .swiftlint.yml diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 000000000..9a727f15b --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,10 @@ +variable_name: + min_length: + warning: 1 + error: 0 + +force_try: warning + +disabled_rules: # rule identifiers to exclude from running + - function_body_length + - line_length diff --git a/.travis.yml b/.travis.yml index d5349d803..d5388aa92 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,14 @@ language: objective-c -osx_image: xcode7.3 +osx_image: xcode8 xcode_project: 'xcodeProject/xSwift.xcodeproj' xcode_scheme: 'xSwiftTests' +install: + - brew update && brew install swiftlint + script: - - xcodebuild test -project 'xcodeProject/xSwift.xcodeproj' -scheme 'xSwiftTests' -sdk macosx10.11 + - swiftlint + - xcodebuild test -project 'xcodeProject/xSwift.xcodeproj' -scheme 'xSwiftTests' -sdk macosx10.12 - bin/fetch-configlet - bin/configlet . sudo: false diff --git a/README.md b/README.md index 139371e79..60600d0dc 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,10 @@ Exercism exercises in Swift Please see the [contributing guide](https://github.com/exercism/x-api/blob/master/CONTRIBUTING.md#the-exercise-data) +## Swift Track + +We use Travis CI to automatically run all the unit tests on the code that is going to be checked in. In addition we also have [SwiftLint](https://github.com/realm/SwiftLint) set up to make sure that the code is consistent across all exercises. Please run `swiftlint autocorrect --format` on your code before submitting a PR. Also in order for the tests to run they need to be added to the `xcodeProject` project. Make sure all the tests pass locally and that you are using the latest Xcode version otherwise the Travis checks may fail. + ## License The MIT License (MIT) diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index fef3803f9..9ef2bd87d 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -1,6 +1,6 @@ ## Installing Swift -In order to use Swift, you must be running Xcode version 7.3 or greater which is available at [Apple's developer center](https://developer.apple.com/xcode/downloads/). +In order to use Swift, you must be running Xcode version 8.0 or greater which is available at [Apple's developer center](https://developer.apple.com/xcode/downloads/). -All exercises tested with Xcode 7.3 using Swift 2.2 +All exercises tested with Xcode 8.0 using Swift 3 diff --git a/docs/LEARNING.md b/docs/LEARNING.md index c54312a2c..4cd070205 100644 --- a/docs/LEARNING.md +++ b/docs/LEARNING.md @@ -2,5 +2,5 @@ Exercism provides exercises and feedback, but it can be difficult to jump into learning Swift for the first time. These resources can help you get started: -* [Swifty App](https://itunes.apple.com/us/app/swifty-learn-how-to-code-in/id886315617?mt=8), by Johannes Berger -* [The Swift Programming Language](https://itunes.apple.com/us/book/the-swift-programming-language/id881256329?mt=11), by Apple +* [Apple Swift Website](http://www.apple.com/swift/) +* [The Swift Programming Language Website](https://swift.org/documentation/) diff --git a/exercises/accumulate/AccumulateExample.swift b/exercises/accumulate/AccumulateExample.swift index e94197af9..8f55d9476 100644 --- a/exercises/accumulate/AccumulateExample.swift +++ b/exercises/accumulate/AccumulateExample.swift @@ -1,9 +1,5 @@ - -// Foundation not needed - - extension Array { - func accumulate(yield: (Element) -> S) -> [S] { + func accumulate(_ yield: (Element) -> S) -> [S] { var result: [S] = [S]() for item in self { result.append(yield(item)) diff --git a/exercises/accumulate/AccumulateTest.swift b/exercises/accumulate/AccumulateTest.swift index 830bc5f1b..e3d0a3e09 100644 --- a/exercises/accumulate/AccumulateTest.swift +++ b/exercises/accumulate/AccumulateTest.swift @@ -1,98 +1,91 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif private extension String { - + var length: Int {return self.characters.count} - + func reverse() -> String { - var result:String = "" + var result: String = "" for char in self.characters { result = "\(char)\(result)" } return result } - + } class AccumulateTest: XCTestCase { - func testEmptyAccumulation() { + func testEmptyAccumulation() { - let input = [Int]() - func square(input:Int) -> Int { + let input = [Int]() + func square(_ input: Int) -> Int { return input * input - } - let result = input.accumulate(square) - + } + let result = input.accumulate(square) + XCTAssertTrue(result.isEmpty) } func testAccumulateSquares() { - - let input = [1,2,3,4] - let expected = [1,4,9,16] - func square(input:Int) -> Int { + + let input = [1, 2, 3, 4] + let expected = [1, 4, 9, 16] + func square(_ input: Int) -> Int { return input * input } - + let result = input.accumulate(square) - + XCTAssertEqual(expected, result) } - - func testAccumulateUpcases() { - - let input = ["hello","world"] - let expected = ["HELLO","WORLD"] - func toUpper(input:String) -> String { - return input.uppercaseString + + let input = ["hello", "world"] + let expected = ["HELLO", "WORLD"] + func toUpper(_ input: String) -> String { + return input.uppercased() } - + let result = input.accumulate(toUpper) - + XCTAssertEqual(expected, result) - } - - + } func testAccumulateReversedStrings() { - - let input = ["the","quick","brown","fox","etc"] - let expected = ["eht","kciuq","nworb","xof","cte"] - func reverse(input:String) -> String { + + let input = ["the", "quick", "brown", "fox", "etc"] + let expected = ["eht", "kciuq", "nworb", "xof", "cte"] + func reverse(_ input: String) -> String { return input.reverse() } - + let result = input.accumulate(reverse) - + XCTAssertEqual(expected, result) } - + func testAccumulateRecursively() { - - let input = ["a","b","c"] + + let input = ["a", "b", "c"] let expected = [ - ["a1","a2","a3"], - ["b1","b2","b3"], - ["c1","c2","c3"] + ["a1", "a2", "a3"], + ["b1", "b2", "b3"], + ["c1", "c2", "c3"] ] - - func recurse(input:String) -> [String] { - func appendTo(innerInput:String) -> String { + + func recurse(_ input: String) -> [String] { + func appendTo(_ innerInput: String) -> String { return input+innerInput } - let result = ["1","2","3"].accumulate(appendTo) + let result = ["1", "2", "3"].accumulate(appendTo) return result } - - let result = input.accumulate(recurse) - + XCTAssertEqual(expected, result) } } diff --git a/exercises/acronym/AcronymExample.swift b/exercises/acronym/AcronymExample.swift index 358d93c6f..54209257e 100644 --- a/exercises/acronym/AcronymExample.swift +++ b/exercises/acronym/AcronymExample.swift @@ -1,55 +1,51 @@ -// Foundation not needed +private extension String { - - -private extension String{ - - func substringWithRangeInt(intRange:Range)->String{ - let start = self.startIndex.advancedBy(intRange.startIndex) - let end = self.startIndex.advancedBy(intRange.endIndex) - return self.substringWithRange(start..) -> String { + let start = self.characters.index(self.startIndex, offsetBy: intRange.lowerBound) + let end = self.characters.index(self.startIndex, offsetBy: intRange.upperBound) + return self.substring(with: start.. String{ + + func substringWithRangeInt(start: Int, end: Int) -> String { let range = start.. String { - - var previousLetter:String = "" - - func splitCamelcaseAt(currentLetter: String, inout withString previousLetter: String ) -> Bool { - +struct Acronym { + + static func abbreviate(_ inString: String) -> String { + + var previousLetter: String = "" + + func splitCamelcaseAt(_ currentLetter: String, withString previousLetter: inout String ) -> Bool { + defer { previousLetter = currentLetter } - + if currentLetter == " " { return false } else if currentLetter.isEmpty { return false - } else if (previousLetter.isLowercase && currentLetter.isUppercase){ + } else if (previousLetter.isLowercase && currentLetter.isUppercase) { //previousLetter = currentLetter // see defer block return true } //previousLetter = currentLetter // see defer block return false } - - func insertSpaceAtCamelcase(inString:String)->String{ + + func insertSpaceAtCamelcase(_ inString: String) -> String { var accumulate = "" var lastIndexAdded = 0 - - for (index , each) in inString.characters.map({String($0)}).enumerate() { - if splitCamelcaseAt(each, withString: &previousLetter){ + + for (index, each) in inString.characters.map({String($0)}).enumerated() { + if splitCamelcaseAt(each, withString: &previousLetter) { accumulate += inString.substringWithRangeInt(start: lastIndexAdded, end: index)+" " // inserts a space lastIndexAdded = index } @@ -57,24 +53,22 @@ struct Acronym{ let lastStringSection = inString.substringWithRangeInt(start: lastIndexAdded, end: inString.characters.count) return accumulate + lastStringSection } - - func splitAt(characterToCompare:Character, charToSplitAt:String = " ,-:")-> Bool{ - for each in charToSplitAt.characters{ - if each == characterToCompare{ + + func splitAt(_ characterToCompare: Character, charToSplitAt: String = " ,-:") -> Bool { + for each in charToSplitAt.characters { + if each == characterToCompare { return true } } return false } - - func splitStringToArray(inString:String) -> [String]{ - - return inString.characters.split(isSeparator: { splitAt($0) }).map{String($0)} + + func splitStringToArray(_ inString: String) -> [String] { + + return inString.characters.split(isSeparator: { splitAt($0) }).map {String($0)} } - - return splitStringToArray(insertSpaceAtCamelcase(inString)).map({$0.uppercaseString.substringWithRangeInt(start: 0, end: 1)}).joinWithSeparator("") - } - -} + return splitStringToArray(insertSpaceAtCamelcase(inString)).map({$0.uppercased().substringWithRangeInt(start: 0, end: 1)}).joined(separator: "") + } +} diff --git a/exercises/acronym/AcronymTest.swift b/exercises/acronym/AcronymTest.swift index 608e80423..7f95a6629 100644 --- a/exercises/acronym/AcronymTest.swift +++ b/exercises/acronym/AcronymTest.swift @@ -1,32 +1,31 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class AcronymTest: XCTestCase { - - func testAcronymAbbreviateTest1(){ + + func testAcronymAbbreviateTest1() { XCTAssertEqual("PNG", Acronym.abbreviate("Portable Network Graphics")) } - - func testAcronymAbbreviateTest2(){ + + func testAcronymAbbreviateTest2() { XCTAssertEqual("ROR", Acronym.abbreviate("Ruby on Rails")) } - - func testAcronymAbbreviateTest3(){ + + func testAcronymAbbreviateTest3() { XCTAssertEqual("HTML", Acronym.abbreviate("HyperText Markup Language")) } - - func testAcronymAbbreviateTest4(){ + + func testAcronymAbbreviateTest4() { XCTAssertEqual("FIFO", Acronym.abbreviate("First In, First Out")) } - - func testAcronymAbbreviateTest5(){ + + func testAcronymAbbreviateTest5() { XCTAssertEqual("PHP", Acronym.abbreviate("PHP: Hypertext Preprocessor")) } - - func testAcronymAbbreviateTest6(){ + + func testAcronymAbbreviateTest6() { XCTAssertEqual("CMOS", Acronym.abbreviate("Complementary metal-oxide semiconductor")) } - -} \ No newline at end of file + +} diff --git a/exercises/allergies/AllergiesExample.swift b/exercises/allergies/AllergiesExample.swift index 51541579d..21d953618 100644 --- a/exercises/allergies/AllergiesExample.swift +++ b/exercises/allergies/AllergiesExample.swift @@ -1,26 +1,22 @@ -// Foundation not needed - - - enum Allergen: UInt { - case Eggs = 1 - case Peanuts = 2 - case Shellfish = 4 - case Strawberries = 8 - case Tomatoes = 16 - case Chocolate = 32 - case Pollen = 64 - case Cats = 128 + case eggs = 1 + case peanuts = 2 + case shellfish = 4 + case strawberries = 8 + case tomatoes = 16 + case chocolate = 32 + case pollen = 64 + case cats = 128 } struct Allergies { let score: UInt - + init(_ score: UInt) { self.score = UInt(score) } - - func hasAllergy(allergen: Allergen) -> Bool { + + func hasAllergy(_ allergen: Allergen) -> Bool { return allergen.rawValue & score == allergen.rawValue ? true : false } -} \ No newline at end of file +} diff --git a/exercises/allergies/AllergiesTest.swift b/exercises/allergies/AllergiesTest.swift index cb25d9e80..cc06e7d95 100644 --- a/exercises/allergies/AllergiesTest.swift +++ b/exercises/allergies/AllergiesTest.swift @@ -1,48 +1,47 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class AllergiesTest: XCTestCase { - + func testBob() { - + let allergies = Allergies(34) - - XCTAssertTrue(allergies.hasAllergy(.Peanuts), "Bob is allergic to peanuts") - XCTAssertTrue(allergies.hasAllergy(.Chocolate), "Bob is allergic to chocolate") - XCTAssertFalse(allergies.hasAllergy(.Cats), "Bob is not allergic to cats") + + XCTAssertTrue(allergies.hasAllergy(.peanuts), "Bob is allergic to peanuts") + XCTAssertTrue(allergies.hasAllergy(.chocolate), "Bob is allergic to chocolate") + XCTAssertFalse(allergies.hasAllergy(.cats), "Bob is not allergic to cats") } - + func testEggsNcats() { - + let allergies = Allergies(129) - - XCTAssertTrue(allergies.hasAllergy(.Eggs)) - XCTAssertTrue(allergies.hasAllergy(.Cats)) - XCTAssertFalse(allergies.hasAllergy(.Chocolate)) - + + XCTAssertTrue(allergies.hasAllergy(.eggs)) + XCTAssertTrue(allergies.hasAllergy(.cats)) + XCTAssertFalse(allergies.hasAllergy(.chocolate)) + } - + func testNone() { let allergies = Allergies(0) - - XCTAssertFalse(allergies.hasAllergy(.Pollen)) + + XCTAssertFalse(allergies.hasAllergy(.pollen)) } - + func testAll() { - - let allInt = UInt(Array(0...7).reduce(0){ return ($0 | (1 << $1)) }) + + let allInt = UInt(Array(0...7).reduce(0) { return ($0 | (1 << $1)) }) let allergies = Allergies(allInt) - - XCTAssertTrue(allergies.hasAllergy(.Eggs)) - XCTAssertTrue(allergies.hasAllergy(.Peanuts)) - XCTAssertTrue(allergies.hasAllergy(.Shellfish)) - XCTAssertTrue(allergies.hasAllergy(.Strawberries)) - XCTAssertTrue(allergies.hasAllergy(.Tomatoes)) - XCTAssertTrue(allergies.hasAllergy(.Chocolate)) - XCTAssertTrue(allergies.hasAllergy(.Pollen)) - XCTAssertTrue(allergies.hasAllergy(.Cats)) - + + XCTAssertTrue(allergies.hasAllergy(.eggs)) + XCTAssertTrue(allergies.hasAllergy(.peanuts)) + XCTAssertTrue(allergies.hasAllergy(.shellfish)) + XCTAssertTrue(allergies.hasAllergy(.strawberries)) + XCTAssertTrue(allergies.hasAllergy(.tomatoes)) + XCTAssertTrue(allergies.hasAllergy(.chocolate)) + XCTAssertTrue(allergies.hasAllergy(.pollen)) + XCTAssertTrue(allergies.hasAllergy(.cats)) + } } diff --git a/exercises/anagram/AnagramExample.swift b/exercises/anagram/AnagramExample.swift index 2bda4c09a..547d1e68f 100644 --- a/exercises/anagram/AnagramExample.swift +++ b/exercises/anagram/AnagramExample.swift @@ -1,35 +1,29 @@ -// Foundation not needed - - - struct Anagram { var baseWord = "" init (word: String) { baseWord = word } - - func sortLetters(wordToSort: String) -> String { + + func sortLetters(_ wordToSort: String) -> String { var characters: [String] = [] for char in wordToSort.characters { characters.append("\(char)") } - characters = characters.sort(< ) + characters = characters.sorted(isOrderedBefore: < ) return characters.reduce("", combine: +) } - - func match(words: [String]) -> [String] { + + func match(_ words: [String]) -> [String] { var matches: [String] = [] - + for candidateWord in words { - if sortLetters(baseWord.lowercaseString) == sortLetters(candidateWord.lowercaseString) - && baseWord.lowercaseString != candidateWord.lowercaseString { + if sortLetters(baseWord.lowercased()) == sortLetters(candidateWord.lowercased()) + && baseWord.lowercased() != candidateWord.lowercased() { matches.append(candidateWord) } } - + return matches } - -} - +} diff --git a/exercises/anagram/AnagramTest.swift b/exercises/anagram/AnagramTest.swift index 41b54113b..ea508a6af 100644 --- a/exercises/anagram/AnagramTest.swift +++ b/exercises/anagram/AnagramTest.swift @@ -1,79 +1,76 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class AnagramTest: XCTestCase { - + func testNoMatches() { let anagram = Anagram(word: "diaper") - let results = anagram.match(["hello","world","zombies","pants"]) + let results = anagram.match(["hello", "world", "zombies", "pants"]) let expected = [] XCTAssertEqual(results, expected) } - - func testDetectSimpleAnagram() { let anagram = Anagram(word: "ant") - let results = anagram.match(["tan","stand","at"]) + let results = anagram.match(["tan", "stand", "at"]) let expected = ["tan"] XCTAssertEqual(results, expected) } - + func testDetectMultipleAnagrams() { let anagram = Anagram(word: "master") - let results = anagram.match(["stream","pigeon","maters"]) - let expected = ["stream","maters"] + let results = anagram.match(["stream", "pigeon", "maters"]) + let expected = ["stream", "maters"] XCTAssertEqual(results, expected) } - + func testDoesNotConfuseDifferentDuplicates() { let anagram = Anagram(word: "galea") let results = anagram.match(["eagle"]) let expected = [] XCTAssertEqual(results, expected) } - + func testIdenticalWordIsNotAnagram() { let anagram = Anagram(word: "corn") let results = anagram.match(["corn", "dark", "Corn", "rank", "CORN", "cron", "park"]) let expected = ["cron"] XCTAssertEqual(results, expected) } - + func testEliminateAnagramsWithSameChecksum() { let anagram = Anagram(word: "mass") let results = anagram.match(["last"]) let expected = [] XCTAssertEqual(results, expected) } - + func testEliminateAnagramSubsets() { let anagram = Anagram(word: "good") - let results = anagram.match(["dog","goody"]) + let results = anagram.match(["dog", "goody"]) let expected = [] XCTAssertEqual(results, expected) } - + func testDetectAnagram() { let anagram = Anagram(word: "listen") - let results = anagram.match(["enlists","google","inlets","banana"]) + let results = anagram.match(["enlists", "google", "inlets", "banana"]) let expected = ["inlets"] XCTAssertEqual(results, expected) } - + func testMultipleAnagrams() { let anagram = Anagram(word: "allergy") - let results = anagram.match(["gallery","ballerina","regally","clergy","largely","leading"]) - let expected = ["gallery","regally","largely"] + let results = anagram.match(["gallery", "ballerina", "regally", "clergy", "largely", "leading"]) + let expected = ["gallery", "regally", "largely"] XCTAssertEqual(results, expected) } - + func testAnagramsAreCaseInsensitive() { let anagram = Anagram(word: "Orchestra") - let results = anagram.match(["cashregister","Carthorse","radishes"]) + let results = anagram.match(["cashregister", "Carthorse", "radishes"]) let expected = ["Carthorse"] XCTAssertEqual(results, expected) } - + } diff --git a/exercises/atbash-cipher/AtbashExample.swift b/exercises/atbash-cipher/AtbashExample.swift index c30580131..25c1b0ac6 100644 --- a/exercises/atbash-cipher/AtbashExample.swift +++ b/exercises/atbash-cipher/AtbashExample.swift @@ -1,40 +1,34 @@ -// Foundation not needed - - - struct Atbash { - - private static func stripWhiteSpaceAndPunctuations(input:String) ->String{ + + private static func stripWhiteSpaceAndPunctuations(_ input: String) -> String { var returnString = "" - input.characters.forEach{ - if !" ,.".containsString(String($0)){ + input.characters.forEach { + if !" ,.".contains(String($0)) { returnString.append($0) } } - + return returnString } - - - - static let cipherDictApply:[Character : Character] = ["a": "z", "b": "y", "c": "x", "d": "w", "e": "v", "f": "u", "g": "t", "h": "s", "i": "r", "j": "q", "k": "p", "l": "o", "m": "n", "n": "m", "o": "l", "p": "k", "q": "j", "r": "i", "s": "h", "t": "g", "u": "f", "v": "e", "w": "d", "x": "c", "y": "b", "z": "a"] - - static func encode( valueIn:String)->String{ - let value = stripWhiteSpaceAndPunctuations(valueIn.lowercaseString ) - + + static let cipherDictApply: [Character : Character] = ["a": "z", "b": "y", "c": "x", "d": "w", "e": "v", "f": "u", "g": "t", "h": "s", "i": "r", "j": "q", "k": "p", "l": "o", "m": "n", "n": "m", "o": "l", "p": "k", "q": "j", "r": "i", "s": "h", "t": "g", "u": "f", "v": "e", "w": "d", "x": "c", "y": "b", "z": "a"] + + static func encode( _ valueIn: String) -> String { + let value = stripWhiteSpaceAndPunctuations(valueIn.lowercased() ) + var text2return = "" - - for each in value.characters{ + + for each in value.characters { text2return.append(cipherDictApply[each] ?? each ) } return insertSpace5th(text2return) } - - static func insertSpace5th(value:String)->String{ + + static func insertSpace5th(_ value: String) -> String { var tempCounter = 0 - var tempString:String = "" - for each in value.characters{ - if tempCounter % 5 == 0 && tempCounter != 0{ + var tempString: String = "" + for each in value.characters { + if tempCounter % 5 == 0 && tempCounter != 0 { tempString += " \(each)" } else { tempString += "\(each)" } tempCounter += 1 @@ -42,4 +36,4 @@ struct Atbash { return tempString } -} \ No newline at end of file +} diff --git a/exercises/atbash-cipher/AtbashTest.swift b/exercises/atbash-cipher/AtbashTest.swift index eedb999b0..77d578180 100644 --- a/exercises/atbash-cipher/AtbashTest.swift +++ b/exercises/atbash-cipher/AtbashTest.swift @@ -1,43 +1,42 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class AtbashTest: XCTestCase { - + func testEncodeNo() { XCTAssertEqual("ml", Atbash.encode("no") ) } - + func testEncodeYes() { XCTAssertEqual("bvh", Atbash.encode("yes") ) } - + func testEncodeOMG() { XCTAssertEqual("lnt", Atbash.encode("OMG") ) } - + func testEncodeOMGWithSpaces() { XCTAssertEqual("lnt", Atbash.encode("O M G") ) } - + func testEncodeLongWord() { XCTAssertEqual("nrmwy oldrm tob", Atbash.encode("mindblowingly") ) } - + func testEncodeNumbers() { XCTAssertEqual("gvhgr mt123 gvhgr mt", - Atbash.encode("Testing, 1 2 3, testing.") ) + Atbash.encode("Testing, 1 2 3, testing.") ) } - + func testEncodeSentence() { XCTAssertEqual("gifgs rhurx grlm", Atbash.encode("Truth is fiction.") ) } - + func testEncodeAllTheThings() { let plaintext = "The quick brown fox jumps over the lazy dog." let cipher = "gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt" XCTAssertEqual(cipher, Atbash.encode(plaintext) ) } - + } diff --git a/exercises/binary-search-tree/BinarySearchTreeExample.swift b/exercises/binary-search-tree/BinarySearchTreeExample.swift index 6978d4f3d..8bc022767 100644 --- a/exercises/binary-search-tree/BinarySearchTreeExample.swift +++ b/exercises/binary-search-tree/BinarySearchTreeExample.swift @@ -1,47 +1,66 @@ -// Foundation not needed - -class BinarySearchTree { - - var data: T - var left: BinarySearchTree? - var right: BinarySearchTree? - - init(_ data: T) { - self.data = data - } - - func insert(newData: T) { - if newData <= data { - if let left = left { - left.insert(newData) - } else { - left = BinarySearchTree(newData) - } - } else { - if let right = right { - right.insert(newData) - } else { - right = BinarySearchTree(newData) - } - } +indirect enum BinarySearchTree { + + var data: Element? { + guard case let .node(_, value, _) = self else { return nil } + return value + } + + var left: BinarySearchTree? { + guard case let .node(left, _, _) = self else { return nil } + return left + } + + var right: BinarySearchTree? { + guard case let .node(_, _, right) = self else { return nil } + return right } - - func allData() -> [T] { - return getAllData().sort(<) + + case empty + case node(BinarySearchTree, Element, BinarySearchTree) + + init(left: BinarySearchTree = .empty, + _ value: Element, + right: BinarySearchTree= .empty ) { + self = .node(left, value, right) + } + init() { + self = .empty } - - private func getAllData() -> [T] { - var result = [data] - - if let left = left { - result += left.getAllData() + private func insert ( _ into: BinarySearchTree, _ newValue: Element ) -> BinarySearchTree { + let bailOut = BinarySearchTree(left: .empty, newValue, right: .empty) + + guard case let .node(left, value, right) = into else { return bailOut } + + if newValue <= value { return + BinarySearchTree(left: insert(left, newValue), value, right: right) } - - if let right = right { - result += right.getAllData() + + if value <= newValue { return + BinarySearchTree(left: left, value, right: insert(right, newValue)) } - + + return .node(left, value, right) + } + mutating func insert( _ newValue: Element ) { + + guard case let .node(left, value, right) = insert(self, newValue) else { return } + + self = .node(left, value, right) + } + + private func getAllData() -> [Element] { + + guard case let .node( left, value, right) = self else { return [] } + var result = [value] + + result += left.getAllData() + result += right.getAllData() + return result + + } + + func allData() -> [Element] { + return getAllData().sorted(isOrderedBefore: <) } - -} \ No newline at end of file +} diff --git a/exercises/binary-search-tree/BinarySearchTreeTest.swift b/exercises/binary-search-tree/BinarySearchTreeTest.swift index c0fd94085..648c343c9 100644 --- a/exercises/binary-search-tree/BinarySearchTreeTest.swift +++ b/exercises/binary-search-tree/BinarySearchTreeTest.swift @@ -1,34 +1,34 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class BinarySearchTreeTest: XCTestCase { - + func testDataIsRetained() { XCTAssertEqual(4, BinarySearchTree(4).data) } - + func testInsertingLess() { var four = BinarySearchTree(4) four.insert(2) XCTAssertEqual(4, four.data) XCTAssertEqual(2, four.left?.data) } - + func testInsertingSame() { var four = BinarySearchTree(4) four.insert(4) XCTAssertEqual(4, four.data) XCTAssertEqual(4, four.left?.data) } - + func testInsertingRight() { var four = BinarySearchTree(4) four.insert(5) XCTAssertEqual(4, four.data) XCTAssertEqual(5, four.right?.data) } - + func testComplexTree() { var four = BinarySearchTree(4) four.insert(2) @@ -45,17 +45,17 @@ class BinarySearchTreeTest: XCTestCase { XCTAssertEqual(5, four.right?.left?.data) XCTAssertEqual(7, four.right?.right?.data) } - + func testAllDataForOneElement() { XCTAssertEqual([4], BinarySearchTree(4).allData()) } - + func testAllDataForSmallerElement() { var four = BinarySearchTree(4) four.insert(2) XCTAssertEqual([2, 4], four.allData()) } - + func testAllDataForLargerElement() { var four = BinarySearchTree(4) four.insert(5) @@ -72,5 +72,5 @@ class BinarySearchTreeTest: XCTestCase { four.insert(5) XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], four.allData()) } - + } diff --git a/exercises/binary-search/BinarySearchExample.swift b/exercises/binary-search/BinarySearchExample.swift index adb9828d2..781d3f19a 100644 --- a/exercises/binary-search/BinarySearchExample.swift +++ b/exercises/binary-search/BinarySearchExample.swift @@ -1,44 +1,24 @@ -// Foundation not needed - - - -// Note: Placing this enum inside the BinarySearch struct results in a compiler crash - -#if swift(>=3.0) - enum BinarySearchError: ErrorProtocol { - case Unsorted - } -#else - enum BinarySearchError: ErrorType { - case Unsorted - } -#endif +enum BinarySearchError: ErrorProtocol { + case unsorted +} struct BinarySearch { - + let list: [T] var middle: Int { return list.count / 2 } - + init(_ list: [T]) throws { - #if swift(>=3.0) guard list == list.sorted(isOrderedBefore: <) else { - throw BinarySearchError.Unsorted + throw BinarySearchError.unsorted } - #else - guard list == list.sort(<) else { - throw BinarySearchError.Unsorted - } - - #endif - self.list = list } - - func searchFor(datum: T) -> Int? { + + func searchFor(_ datum: T) -> Int? { let middleItem = list[middle] - + if middleItem == datum { return middle } else if middleItem > datum { @@ -46,16 +26,13 @@ struct BinarySearch { guard sublist != list else { return nil } - - // try! is safe here, since it's not possible to get here if the data isn't initially sorted return try! BinarySearch(sublist).searchFor(datum) } else { let sublist = Array(list[middle.. { } } } - -} \ No newline at end of file + +} diff --git a/exercises/binary-search/BinarySearchTest.swift b/exercises/binary-search/BinarySearchTest.swift index 1f5962852..8e1870281 100644 --- a/exercises/binary-search/BinarySearchTest.swift +++ b/exercises/binary-search/BinarySearchTest.swift @@ -1,9 +1,9 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class BinarySearchTest: XCTestCase { - + func testHasListData() { let binary = try! BinarySearch([1, 3, 4, 6, 8, 9, 11]) XCTAssertEqual([1, 3, 4, 6, 8, 9, 11], binary.list) @@ -11,14 +11,14 @@ class BinarySearchTest: XCTestCase { func testThrowsErrorForUnsortedList() { var throwsUnsortedError = false - + defer { XCTAssertTrue(throwsUnsortedError) } - + do { let _ = try BinarySearch([2, 1, 4, 3, 6]) - } catch BinarySearchError.Unsorted { + } catch BinarySearchError.unsorted { throwsUnsortedError = true } catch { return @@ -28,23 +28,23 @@ class BinarySearchTest: XCTestCase { func testNilForDataNotInList() { XCTAssertNil(try! BinarySearch([1, 3, 6]).searchFor(2)) } - + func testFindsPositionOfMiddleItem() { let binary = try! BinarySearch([1, 3, 4, 6, 8, 9, 11]) - XCTAssertEqual(3, binary.middle) + XCTAssertEqual(3, binary.middle) } - + func testFindsPositionOfSearchData() { let binary = try! BinarySearch([1, 3, 4, 6, 8, 9, 11]) XCTAssertEqual(5, binary.searchFor(9)) } - + func testFindsPositionInALargerList() { let binary = try! BinarySearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144]) XCTAssertEqual(1, binary.searchFor(3)) XCTAssertEqual(7, binary.searchFor(55)) } - + func testFindsCorrectPositionInAListWithAnEvenNumberOfElements() { let binary = try! BinarySearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]) XCTAssertEqual(5, binary.searchFor(21)) diff --git a/exercises/binary/BinaryExample.swift b/exercises/binary/BinaryExample.swift index 2df95da01..c78c3f44a 100644 --- a/exercises/binary/BinaryExample.swift +++ b/exercises/binary/BinaryExample.swift @@ -1,24 +1,18 @@ -// Foundation not needed - - - -extension Int{ - init(_ value:Binary?){ +extension Int { + init(_ value: Binary?) { if let value = value { - self = value.toDecimal + self = value.toDecimal } else { - self = 0 } + self = 0 } } } - - struct Binary { - private var UIntValue:UInt = 0 - private var toDecimal:Int {get {return Int(UIntValue)}} - private func bi2Uint(input:String) -> UInt?{ - let orderedInput = Array(input.characters.reverse()) - var tempUInt:UInt = 0 - for (inx,each) in orderedInput.enumerate(){ + private var UIntValue: UInt = 0 + private var toDecimal: Int {get {return Int(UIntValue)}} + private func bi2Uint(_ input: String) -> UInt? { + let orderedInput = Array(input.characters.reversed()) + var tempUInt: UInt = 0 + for (inx, each) in orderedInput.enumerated() { if each == "1" { tempUInt += UInt(0x1 << inx) } @@ -28,13 +22,13 @@ struct Binary { } return tempUInt } - - init?(_ input:String){ + + init?(_ input: String) { if bi2Uint(input) != nil { - self.UIntValue = bi2Uint(input)! + self.UIntValue = bi2Uint(input)! } else { - return nil + return nil } - + } -} \ No newline at end of file +} diff --git a/exercises/binary/BinaryTest.swift b/exercises/binary/BinaryTest.swift index d15979113..8e8c4bbcd 100644 --- a/exercises/binary/BinaryTest.swift +++ b/exercises/binary/BinaryTest.swift @@ -1,54 +1,54 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class BinaryTest: XCTestCase { - + func testBinary0IsDecimal0() { XCTAssertEqual( 0, Int(Binary("0"))) } - + func testBinary1isDecimal1() { XCTAssertEqual( 1, Int(Binary("1"))) } - + func testBinary10isDecimal2() { XCTAssertEqual( 2, Int(Binary("10"))) } - + func testBinary11isDecimal3() { XCTAssertEqual( 3, Int(Binary("11"))) } - + func testBinary100isDecimal4() { XCTAssertEqual( 4, Int(Binary("100"))) } - + func testBinary1001isDecimal9() { XCTAssertEqual( 9, Int(Binary("1001"))) } - + func testBinary11010isDecimal26() { XCTAssertEqual( 26, Int(Binary("11010"))) } - + func testBinary10001101000isDecimal1128() { XCTAssertEqual( 1128, Int(Binary("10001101000"))) } - + func testBinaryIgnoresLeadingZeros() { XCTAssertEqual( 31, Int(Binary("000011111"))) } - + func testInvalidBinaryIsDecimal0() { XCTAssertNil ( Binary("carrot123")) } - + func testInvalidBinaryNumbers() { XCTAssertNil ( Binary("012")) XCTAssertNil ( Binary("10nope")) XCTAssertNil ( Binary("nope10")) } - + } diff --git a/exercises/bob/BobExample.swift b/exercises/bob/BobExample.swift index 109a7ae98..67fdfd708 100644 --- a/exercises/bob/BobExample.swift +++ b/exercises/bob/BobExample.swift @@ -1,75 +1,61 @@ -// Foundation not needed - - - private extension String { - - func trimWhiteSpace()-> String{ + + func trimWhiteSpace() -> String { let removeSpaces = trimCharacters(" ", sourceText: self) - if removeSpaces.hasSuffix("\n"){ + if removeSpaces.hasSuffix("\n") { return String(removeSpaces.characters.dropLast()) } return removeSpaces } - - func trimCharacters(charToTrim:Character, sourceText:String) -> String{ + + func trimCharacters(_ charToTrim: Character, sourceText: String) -> String { var editCharacterView = sourceText.characters var editString = String(editCharacterView) - + let trimFirst = sourceText.characters.first == charToTrim let trimLast = sourceText.characters.last == charToTrim - + if trimFirst { editCharacterView = editCharacterView.dropFirst() } if trimLast { editCharacterView = editCharacterView.dropLast() } - + if trimFirst || trimLast == true { editString = trimCharacters(charToTrim, sourceText: String(editCharacterView)) } return editString } - - - var isQuestion:Bool { + var isQuestion: Bool { return hasSuffix("?") } - - var hasLetters:Bool { + + var hasLetters: Bool { return containsLetters(self) } - - var isShouting:Bool { - #if swift(>=3.0) - return (self == uppercased() && hasLetters) - #else - return (self == uppercaseString && hasLetters) - #endif + + var isShouting: Bool { + return (self == uppercased() && hasLetters) + } - - private func containsLetters(input:String) ->Bool{ + + private func containsLetters(_ input: String) -> Bool { let abc = "abcdefghijklmnopqrstuvwxyz" var contains = false let inputStringCollection = input.characters.map({String($0)}) let abcStringCollection = abc.characters.map({String($0)}) - + for each in inputStringCollection { abcStringCollection.forEach({ - - #if swift(>=3.0) - if each == $0 || each == $0.uppercased() { - contains = true } - #else - if each == $0 || each == $0.uppercaseString { + if each == $0 || each == $0.uppercased() { contains = true } - #endif + }) } return contains } - + } struct Bob { - static func hey(input: String) -> String { + static func hey(_ input: String) -> String { if input.trimWhiteSpace().isEmpty { return "Fine, be that way." } else if input.isShouting { @@ -80,6 +66,5 @@ struct Bob { return "Whatever." } } - -} +} diff --git a/exercises/bob/BobTest.swift b/exercises/bob/BobTest.swift index 5b2f6eafc..918779df8 100644 --- a/exercises/bob/BobTest.swift +++ b/exercises/bob/BobTest.swift @@ -1,126 +1,126 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class BobTest: XCTestCase { - + func testStatingSomething() { let input = "Tom-ay-to, tom-aaaah-to." let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testShouting() { let input = "WATCH OUT!" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testAskingAQustion() { let input = "Does this cryogenic chamber make me look fat?" let expected = "Sure." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testTalkingForcefully() { let input = "Let's go make out behind the gym!" let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testUsingAcronyms() { let input = "It's OK if you don't want to go to the DMV." let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testForcefulQuestions() { let input = "WHAT THE HELL WERE YOU THINKING?" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testShoutingNumbers() { let input = "1, 2, 3 GO!" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testOnlyNumbers() { let input = "1, 2, 3." let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testQuestionWithOnlyNumbers() { let input = "4?" let expected = "Sure." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testShoutingWithSpecialCharacters() { let input = "ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testShoutingWithUmlautsCharacters() { let input = "ÄMLÄTS!" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testCalmlySpeakingAboutUmlauts() { let input = "ÄMLäTS!" let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testShoutingWithNoExclamationmark() { let input = "I HATE YOU" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testStatementContainingQuestionsMark() { let input = "Ending with a ? means a question." let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testPrattlingOn() { let input = "Wait! Hang on. Are you going to be OK?" let expected = "Sure." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testSilence() { let input = "" let expected = "Fine, be that way." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testProlongedSilence() { let input = " " let expected = "Fine, be that way." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + } diff --git a/exercises/clock/ClockExample.swift b/exercises/clock/ClockExample.swift index 4a9a8ea9c..1e0d27412 100644 --- a/exercises/clock/ClockExample.swift +++ b/exercises/clock/ClockExample.swift @@ -1,33 +1,31 @@ -// Foundation not needed - struct Clock: Equatable, CustomStringConvertible { - + var hours: Int var minutes: Int - + init(hours: Int, minutes: Int = 0) { self.hours = hours self.minutes = minutes normalize() } - + var description: String { return self.toString } - - func add(minutes minutes:Int) -> Clock { + + func add(minutes: Int) -> Clock { return Clock(hours: self.hours, minutes: self.minutes + minutes) } - - func subtract(minutes minutes:Int) -> Clock { + + func subtract(minutes: Int) -> Clock { return add(minutes: -minutes) } - + private var toString: String { let h = String(format: "%02d", self.hours) let m = String(format: "%02d", self.minutes) - + return h + ":" + m } - + private mutating func normalize() { if minutes >= 60 { self.hours += self.minutes / 60 @@ -44,7 +42,7 @@ struct Clock: Equatable, CustomStringConvertible { self.hours += 24 } } - + } private extension String { @@ -55,4 +53,4 @@ private extension String { func == (lhs: Clock, rhs: Clock) -> Bool { return lhs.description == rhs.description -} \ No newline at end of file +} diff --git a/exercises/clock/ClockTest.swift b/exercises/clock/ClockTest.swift index d3cb257b7..63f570fe5 100644 --- a/exercises/clock/ClockTest.swift +++ b/exercises/clock/ClockTest.swift @@ -1,215 +1,215 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif // Test for Protocols: CustomStringConvertible, Equatable class ClockTest: XCTestCase { - + // MARK: - Create: Test creating a new clock with an initial time. - + func testOnTheHour() { XCTAssertEqual("08:00", Clock(hours: 8).description) } - + func testPastTheHour() { XCTAssertEqual("11:09", Clock(hours: 11, minutes: 9).description) } - + func testMidnightIsZeroHours() { XCTAssertEqual("00:00", Clock(hours: 24).description) } - + func testHourRollsOver() { XCTAssertEqual("01:00", Clock(hours: 25).description) } - + func testHourRollsOverContinuously() { XCTAssertEqual("04:00", Clock(hours: 100).description) } - + func testSixtyMinutesIsNextHour() { XCTAssertEqual("02:00", Clock(hours: 1, minutes: 60).description) } - + func testMinutesRollOver() { XCTAssertEqual("02:40", Clock(hours: 0, minutes: 160).description) } - + func testMinutesRollOverContinuously() { XCTAssertEqual("04:43", Clock(hours: 0, minutes: 1723).description) } - + func testHoursAndMinutesRollOver() { XCTAssertEqual("11:01", Clock(hours: 201, minutes: 3001).description) } - + func testHoursAndMinutesRollOverToExactlyMidnight() { XCTAssertEqual("00:00", Clock(hours: 72, minutes: 8640).description) } - + func testNegativeHour() { XCTAssertEqual("23:15", Clock(hours: -1, minutes: 15).description) } - + func testNegativeHourRollsOver() { XCTAssertEqual("23:00", Clock(hours: -25).description) } - + func testNegativeHourRollsOverContinuously() { XCTAssertEqual("05:00", Clock(hours: -91).description) } - + func testNegativeMinutes() { XCTAssertEqual("00:20", Clock(hours: 1, minutes: -40).description) } - + func testNegativeMinutesRollOver() { XCTAssertEqual("22:20", Clock(hours: 1, minutes: -160).description) } - + func testNegativeMinutesRollOverContinuously() { XCTAssertEqual("16:40", Clock(hours: 1, minutes: -4820).description) } - + func testNegativeHoursAndMinutesBothRollOverContinuously() { XCTAssertEqual("22:10", Clock(hours: -121, minutes: -5810).description) } - + // MARK: - Add: Test adding and subtracting minutes. - + func testAddMinutes() { let clock = Clock(hours: 10).add(minutes: 3) XCTAssertEqual("10:03", clock.description) } - + func testAddNoMinutes() { let clock = Clock(hours: 6, minutes: 41).add(minutes: 0) XCTAssertEqual("06:41", clock.description) } - + func testAddToNextHour() { let clock = Clock(hours: 0, minutes: 45).add(minutes: 40) XCTAssertEqual("01:25", clock.description) } - + func testAddMoreThanOneHour() { let clock = Clock(hours: 10).add(minutes: 61) XCTAssertEqual("11:01", String(clock)) } - + func testAddMoreThanTwoHoursWithCarry() { let clock = Clock(hours: 0, minutes: 45).add(minutes: 160) XCTAssertEqual("03:25", clock.description) } - + func testAddAcrossMidnight() { let clock = Clock(hours: 23, minutes: 59).add(minutes: 2) XCTAssertEqual("00:01", String(clock)) } - + func testAddMoreThanOneDay() { // (1500 min = 25 hrs) let clock = Clock(hours: 5, minutes: 32).add(minutes: 1500) XCTAssertEqual("06:32", String(clock)) } - + func testAddMoreThanTwoDays() { let clock = Clock(hours: 1, minutes: 1).add(minutes: 3500) XCTAssertEqual("11:21", String(clock)) } - + func testSubtractMinutes() { let clock = Clock(hours: 10, minutes: 3).subtract(minutes: 3) XCTAssertEqual("10:00", String(clock)) } - + func testSubtractToPreviousHour() { let clock = Clock(hours: 10, minutes: 3).subtract(minutes: 30) XCTAssertEqual("09:33", String(clock)) } - + func testSubtractMoreThanAnHour() { let clock = Clock(hours: 10, minutes: 3).subtract(minutes: 70) XCTAssertEqual("08:53", String(clock)) } - + func testSubtractAcrossMidnight() { let clock = Clock(hours: 0, minutes: 3).subtract(minutes: 4) XCTAssertEqual("23:59", String(clock)) } - + func testSubtractMoreThanTwoHours() { let clock = Clock(hours: 0, minutes: 0).subtract(minutes: 160) XCTAssertEqual("21:20", String(clock)) } - + func testSubtractMoreTHanTwoHoursWithBorrow() { let clock = Clock(hours: 6, minutes: 15).subtract(minutes: 160) XCTAssertEqual("03:35", String(clock)) } - + func testSubtractMoreThanOneDay() { // (1500 min = 25 hrs) let clock = Clock(hours: 5, minutes: 32).subtract(minutes: 1500) XCTAssertEqual("04:32", String(clock)) } - + func testSubtractMoreThanTwoDays() { let clock = Clock(hours: 2, minutes: 20).subtract(minutes: 3000) XCTAssertEqual("00:20", String(clock)) } - + // MARK: - Equal: Construct two separate clocks, set times, test if they are equal. - + func testClocksWithSameTime() { let clock1 = Clock(hours: 15, minutes: 37) let clock2 = Clock(hours: 15, minutes: 37) XCTAssertEqual(clock1, clock2) } - + func testClocksAMinuteApart() { let clock1 = Clock(hours: 15, minutes: 36) let clock2 = Clock(hours: 15, minutes: 37) XCTAssertNotEqual(clock1, clock2) } - + func testClocksAnHourApart() { let clock1 = Clock(hours: 14, minutes: 37) let clock2 = Clock(hours: 15, minutes: 37) XCTAssertNotEqual(clock1, clock2) } - + func testClocksWithHourOverflow() { let clock1 = Clock(hours: 10, minutes: 37) let clock2 = Clock(hours: 34, minutes: 37) XCTAssertEqual(clock1, clock2) } - + func testClocksWithHourOverflowBySeveralDays() { let clock1 = Clock(hours: 3, minutes: 11) let clock2 = Clock(hours: 99, minutes: 11) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeHour() { let clock1 = Clock(hours: 22, minutes: 40) let clock2 = Clock(hours: -2, minutes: 40) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeHourThatWraps() { let clock1 = Clock(hours: 17, minutes: 3) let clock2 = Clock(hours: -31, minutes: 3) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeHourThatWrapsMultipleTimes() { let clock1 = Clock(hours: 13, minutes: 49) let clock2 = Clock(hours: -83, minutes: 49) XCTAssertEqual(clock1, clock2) } - + func testClocksWithMinuteOverflow() { let clock1 = Clock(hours: 0, minutes: 1) let clock2 = Clock(hours: 0, minutes: 1441) @@ -221,35 +221,35 @@ class ClockTest: XCTestCase { let clock2 = Clock(hours: 2, minutes: 4322) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeMinute() { let clock1 = Clock(hours: 2, minutes: 40) let clock2 = Clock(hours: 3, minutes: -20) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeMinuteThatWraps() { let clock1 = Clock(hours: 4, minutes: 10) let clock2 = Clock(hours: 5, minutes: -1490) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeMinuteThatWrapsMultipleTimes() { let clock1 = Clock(hours: 6, minutes: 15) let clock2 = Clock(hours: 6, minutes: -4305) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeHoursAndMinutes() { let clock1 = Clock(hours: 7, minutes: 32) let clock2 = Clock(hours: -12, minutes: -268) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeHoursAndMinutesThatWrap() { let clock1 = Clock(hours: 18, minutes: 7) let clock2 = Clock(hours: -54, minutes: -11513) XCTAssertEqual(clock1, clock2) } - + } diff --git a/exercises/crypto-square/CryptoSquareExample.swift b/exercises/crypto-square/CryptoSquareExample.swift index 9b8a47a12..3dfc02597 100644 --- a/exercises/crypto-square/CryptoSquareExample.swift +++ b/exercises/crypto-square/CryptoSquareExample.swift @@ -1,101 +1,82 @@ import Darwin - - private extension String { - - func stripCharacters(charToRemove:String) -> String{ + + func stripCharacters(_ charToRemove: String) -> String { var returnString = "" - self.characters.forEach{ - if !charToRemove.containsString(String($0)){ + self.characters.forEach { + if !charToRemove.contains(String($0)) { returnString.append($0) }} return returnString } - - var stripWhiteSpace:String { return stripCharacters(" ") } - var stripPunctuations:String { return stripCharacters(",.!?") } - var stripSymbols:String { return stripCharacters("#$%^&") } - - -} - + var stripWhiteSpace: String { return stripCharacters(" ") } + var stripPunctuations: String { return stripCharacters(",.!?") } + var stripSymbols: String { return stripCharacters("#$%^&") } +} struct Crypto { - - func segmentSorter(value:String, spacing:Int)->[String]{ + + func segmentSorter(_ value: String, spacing: Int) -> [String] { var tempCounter = 0 - var tempString:String = "" - for each in value.characters{ - if tempCounter % spacing == 0 && tempCounter != 0{ + var tempString: String = "" + for each in value.characters { + if tempCounter % spacing == 0 && tempCounter != 0 { tempString += " \(each)" } else { tempString += "\(each)" } tempCounter += 1 } - return (tempString.componentsSeparatedByString(" ") ) + return (tempString.components(separatedBy: " ") ) } - - func getSquareSize(text:String, floorNoCeling:Bool = false)->Int - { + + func getSquareSize(_ text: String, floorNoCeling: Bool = false) -> Int { let tempDouble = Double(text.characters.count) let tempRoot = sqrt(tempDouble) let tempCeil = ceil(tempRoot) let tempFloor = floor(tempRoot) - if floorNoCeling{ return Int(tempFloor)} else { + if floorNoCeling { return Int(tempFloor)} else { return Int(tempCeil)} } - - func normalizer(textInput:String)->String{ - return textInput.stripSymbols.stripPunctuations.stripWhiteSpace.lowercaseString + + func normalizer(_ textInput: String) -> String { + return textInput.stripSymbols.stripPunctuations.stripWhiteSpace.lowercased() } - - var ciphertext:String { - - var plaintextSegmentsArray = [[Character]]() - - for each in plaintextSegments{ - plaintextSegmentsArray.append(Array(each.characters)) - } - - var ciphertextReturn = "" - - - for i in 0 ..< plaintextSegmentsArray[0].count { - for e in 0 ..< plaintextSegmentsArray.count { - if i < plaintextSegmentsArray[e].count{ - ciphertextReturn.append(plaintextSegmentsArray[e][i]) - } - }} - - return ciphertextReturn - + + var ciphertext: String { + + var plaintextSegmentsArray = [[Character]]() + + for each in plaintextSegments { + plaintextSegmentsArray.append(Array(each.characters)) + } + + var ciphertextReturn = "" + for i in 0 ..< plaintextSegmentsArray[0].count { + for e in 0 ..< plaintextSegmentsArray.count { + if i < plaintextSegmentsArray[e].count { + ciphertextReturn.append(plaintextSegmentsArray[e][i]) + } + }} + + return ciphertextReturn + } - - var normalizeCiphertext:String { - - let sizeNormal:Int = (ciphertext.characters.count == self.size * self.size ) ? getSquareSize(self.ciphertext) : getSquareSize(self.ciphertext, floorNoCeling: true) - - return segmentSorter(ciphertext, spacing: sizeNormal).joinWithSeparator(" ") + + var normalizeCiphertext: String { + + let sizeNormal: Int = (ciphertext.characters.count == self.size * self.size ) ? getSquareSize(self.ciphertext) : getSquareSize(self.ciphertext, floorNoCeling: true) + + return segmentSorter(ciphertext, spacing: sizeNormal).joined(separator: " ") } - - - var plaintextSegments:[String]{ get{ return segmentSorter(self.normalizePlaintext, spacing: self.size)}} - - - var textValue:String = "" - var normalizePlaintext:String = "" - var size:Int = 0 - - init (_ value:String){ + var plaintextSegments: [String] { get { return segmentSorter(self.normalizePlaintext, spacing: self.size)}} + var textValue: String = "" + var normalizePlaintext: String = "" + var size: Int = 0 + + init (_ value: String) { self.textValue = value self.normalizePlaintext = normalizer(value) self.size = getSquareSize(self.normalizePlaintext) } } - - - - - - diff --git a/exercises/crypto-square/CryptoSquareTest.swift b/exercises/crypto-square/CryptoSquareTest.swift index a94a9e7fa..558fe5666 100644 --- a/exercises/crypto-square/CryptoSquareTest.swift +++ b/exercises/crypto-square/CryptoSquareTest.swift @@ -1,24 +1,24 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class CryptoSquareTest: XCTestCase { - + func testNormalizeStrangeCharacters() { let crypto = Crypto("s#$%^&plunk") XCTAssertEqual("splunk", crypto.normalizePlaintext) } - + func testNormalizeUppercaseCharacters() { let crypto = Crypto("WHOA HEY!") XCTAssertEqual("whoahey", crypto.normalizePlaintext) } - + func testNormalizeWithNumbers() { let crypto = Crypto("1, 2, 3 GO!") XCTAssertEqual("123go", crypto.normalizePlaintext) } - + func testSizeOfSmallSquare() { let crypto = Crypto("1234") XCTAssertEqual(2, crypto.size) @@ -28,17 +28,17 @@ class CryptoSquareTest: XCTestCase { let crypto = Crypto("123456789") XCTAssertEqual(3, crypto.size) } - + func testSizeOfNonPerfectSquare() { let crypto = Crypto("123456789abc") XCTAssertEqual(4, crypto.size) } - + func testSizeIsDeterminedByNormalizedPlaintext() { let crypto = Crypto("Oh hey, this is nuts!") XCTAssertEqual(4, crypto.size) } - + func testPlaintextSegments() { let crypto = Crypto("Never vex thine heart with idle woes") let expected = ["neverv", "exthin", "eheart", "withid", "lewoes"] @@ -59,30 +59,28 @@ class CryptoSquareTest: XCTestCase { let crypto = Crypto("We all know interspecies romance is weird.") XCTAssertEqual("wneiaweoreneawssciliprerlneoidktcms", crypto.ciphertext) } - + func testNormalizedCiphertext() { let crypto = Crypto("Vampires are people too!") XCTAssertEqual("vrel aepe mset paoo irpo", crypto.normalizeCiphertext) } - + func testNormalizedCiphertextSpillsIntoShortSegment() { let crypto = Crypto("Madness, and then illumination.") XCTAssertEqual("msemo aanin dninn dlaet ltshu i", crypto.normalizeCiphertext) } - + func testAnotherNormalizedCiphertext() { let crypto = Crypto( "If man was meant to stay on the ground god would have given us roots" - ) - let expected = "imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghns seoau" + ) + let expected = "imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghns seoau" XCTAssertEqual(expected, crypto.normalizeCiphertext) } - + func testNormalizedCiphertextWithPunctuation() { let crypto = Crypto("Have a nice day. Feed the dog & chill out!") let expected = "hifei acedl veeol eddgo aatcu nyhht" XCTAssertEqual(expected, crypto.normalizeCiphertext) } - - -} \ No newline at end of file +} diff --git a/exercises/custom-set/CustomSetExample.swift b/exercises/custom-set/CustomSetExample.swift index 8d02910b7..ff7a9005d 100644 --- a/exercises/custom-set/CustomSetExample.swift +++ b/exercises/custom-set/CustomSetExample.swift @@ -1,108 +1,77 @@ - -// Foundation not needed - - - - func == (lh: CustomSet, rh: CustomSet) -> Bool { - #if swift(>=3.0) - return lh.contents.keys.sorted{$0.hashValue < $1.hashValue} == rh.contents.keys.sorted{$0.hashValue < $1.hashValue} - #else - return lh.contents.keys.sort{$0.hashValue < $1.hashValue} == rh.contents.keys.sort{$0.hashValue < $1.hashValue} - #endif -} + return lh.contents.keys.sorted {$0.hashValue < $1.hashValue} == rh.contents.keys.sorted {$0.hashValue < $1.hashValue} +} +struct CustomSet:Equatable { -struct CustomSet:Equatable{ - typealias Element = T - + private var contents = [Element: Bool]() - - var size:Int {return contents.count} - - - #if swift(>=3.0) - var toSortedArray:[Element] {return Array(contents.keys.sorted{$0.hashValue < $1.hashValue})} + + var size: Int {return contents.count} + + var toSortedArray: [Element] {return Array(contents.keys.sorted {$0.hashValue < $1.hashValue})} init(_ sequence: S) { self.contents = [:] - _ = sequence.map{ self.contents[$0] = true } + _ = sequence.map { self.contents[$0] = true } } - - #else - var toSortedArray:[Element] {return Array(contents.keys.sort{$0.hashValue < $1.hashValue})} - - init(_ sequence: S) { - self.contents = [:] - _ = sequence.map{ self.contents[$0] = true } - } - #endif - - mutating func put(item:Element){ + mutating func put(_ item: Element) { contents[item] = true - + } - - mutating func delete(item:Element){ + + mutating func delete(_ item: Element) { contents[item] = nil - + } - - mutating func removeAll(){ + + mutating func removeAll() { contents = [:] - + } - - func intersection(item:CustomSet)-> CustomSet{ + + func intersection(_ item: CustomSet) -> CustomSet { var temp = [Element: Bool]() - for each in Array(item.contents.keys){ + for each in Array(item.contents.keys) { if (contents[each] != nil) { temp[each] = true } } return CustomSet(temp.keys) } - - - func difference(item:CustomSet)-> CustomSet{ + func difference(_ item: CustomSet) -> CustomSet { var temp = contents - for each in Array(item.contents.keys){ + for each in Array(item.contents.keys) { temp[each] = nil } return CustomSet(temp.keys) } - - func union(item:CustomSet)-> CustomSet{ + + func union(_ item: CustomSet) -> CustomSet { var temp = contents - for each in Array(item.contents.keys){ + for each in Array(item.contents.keys) { temp[each] = true } return CustomSet(temp.keys) } - - - func isSupersetOf (item:CustomSet)-> Bool{ - - return item.contents.count == item.contents.filter{self.contents.keys.contains($0.0)}.count - + func isSupersetOf (_ item: CustomSet) -> Bool { + + return item.contents.count == item.contents.filter {self.contents.keys.contains($0.0)}.count + } - func isDisjoint(item:CustomSet)-> Bool{ - - for each in Array(item.contents.keys){ - if contents.keys.contains(each){ + func isDisjoint(_ item: CustomSet) -> Bool { + + for each in Array(item.contents.keys) { + if contents.keys.contains(each) { return false } } return true } - - func containsMember(item:Element)-> Bool{ + + func containsMember(_ item: Element) -> Bool { if contents[item] != nil { return true} return false } - - - - -} +} diff --git a/exercises/custom-set/CustomSetTest.swift b/exercises/custom-set/CustomSetTest.swift index ca09b05bc..058d7644d 100644 --- a/exercises/custom-set/CustomSetTest.swift +++ b/exercises/custom-set/CustomSetTest.swift @@ -1,92 +1,89 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class CustomSetTest: XCTestCase { - + let emptyTypedArray = [Int]() - - func testEqual(){ + + func testEqual() { XCTAssertEqual(CustomSet([1, 3]), CustomSet([3, 1])) XCTAssertNotEqual(CustomSet([1, 3]), CustomSet([3, 1, 5])) XCTAssertNotEqual(CustomSet([1, 3, 5]), CustomSet([3, 1])) XCTAssertNotEqual(CustomSet([1, 3]), CustomSet([2, 1])) } - - func testNoDuplicates(){ + + func testNoDuplicates() { XCTAssertEqual(CustomSet([1, 1]), CustomSet([1])) } - - func testDeleteMethod(){ - + + func testDeleteMethod() { + var expected1 = CustomSet([3, 2, 1]) expected1.delete(2) XCTAssertEqual(CustomSet([1, 3]), expected1) - + var expected2 = CustomSet([3, 2, 1]) expected2.delete(4) XCTAssertEqual(CustomSet([1, 2, 3]), expected2) } - - func testDifference(){ + + func testDifference() { XCTAssertEqual(CustomSet([1, 3]), - CustomSet([1, 2, 3]).difference(CustomSet([2, 4]))) + CustomSet([1, 2, 3]).difference(CustomSet([2, 4]))) XCTAssertEqual(CustomSet([2, 3]), - CustomSet([1, 2, 3, 4]).difference(CustomSet([1, 4]))) - + CustomSet([1, 2, 3, 4]).difference(CustomSet([1, 4]))) + } - - func testDisjoint(){ + + func testDisjoint() { XCTAssertTrue(CustomSet([1, 2]).isDisjoint(CustomSet([3, 4]))) XCTAssertFalse(CustomSet([1, 2]).isDisjoint(CustomSet([2, 3]))) XCTAssertFalse(CustomSet([1.0, 2.0]).isDisjoint(CustomSet([2.0, 3.0]))) } - - func testEmptyMethod(){ + + func testEmptyMethod() { var expected1 = CustomSet([1, 2]) expected1.removeAll() XCTAssertEqual(CustomSet(emptyTypedArray ), expected1 ) - + var expected2 = CustomSet(emptyTypedArray ) expected2.removeAll() XCTAssertEqual(CustomSet(emptyTypedArray ), expected2 ) } - - - func testIntersection(){ + func testIntersection() { XCTAssertEqual(CustomSet(["a", "c"]), - CustomSet(["a", "b", "c"]).intersection(CustomSet(["a", "c", "d"]))) - + CustomSet(["a", "b", "c"]).intersection(CustomSet(["a", "c", "d"]))) + XCTAssertEqual(CustomSet([3.0]), - CustomSet([1.0, 2.0, 3.0]).intersection(CustomSet([3.0]))) + CustomSet([1.0, 2.0, 3.0]).intersection(CustomSet([3.0]))) } - - func testMember(){ + + func testMember() { XCTAssertTrue(CustomSet([1, 2, 3]).containsMember(2)) XCTAssertTrue(CustomSet([1, 2, 3]).containsMember(3)) XCTAssertFalse(CustomSet([1, 2, 3]).containsMember(4)) } - - func testPutMethod(){ + + func testPutMethod() { var expected1 = CustomSet([1, 2, 4]) expected1.put(3) XCTAssertEqual(CustomSet([1, 2, 3, 4]), - expected1) - + expected1) + var expected2 = CustomSet([1, 2, 3]) expected2.put(3) XCTAssertEqual(CustomSet([1, 2, 3]), - expected2) + expected2) } - - func testSize(){ + + func testSize() { XCTAssertEqual(0, CustomSet(emptyTypedArray).size) XCTAssertEqual(3, CustomSet([1, 2, 3]).size) XCTAssertEqual(3, CustomSet([1, 2, 3, 2]).size) } - - func testSubsetMethod(){ + + func testSubsetMethod() { XCTAssertTrue(CustomSet([1, 2, 3]).isSupersetOf(CustomSet([1, 2, 3]))) XCTAssertTrue(CustomSet([4, 1, 2, 3]).isSupersetOf(CustomSet([1, 2, 3]))) XCTAssertFalse(CustomSet([4, 1, 3]).isSupersetOf(CustomSet([1, 2, 3]))) @@ -94,24 +91,22 @@ class CustomSetTest: XCTestCase { XCTAssertTrue(CustomSet([4, 1, 3]).isSupersetOf(CustomSet(emptyTypedArray))) XCTAssertTrue(CustomSet(emptyTypedArray).isSupersetOf(CustomSet(emptyTypedArray))) } - - func testToA(){ + + func testToA() { XCTAssertEqual([1, 2, 3], CustomSet([3, 1, 2]).toSortedArray) XCTAssertEqual([1, 2, 3], CustomSet([3, 1, 2, 1]).toSortedArray) } - - func testUnion(){ + + func testUnion() { XCTAssertEqual(CustomSet([3, 2, 1]), - CustomSet([1, 3]).union(CustomSet([2]))) + CustomSet([1, 3]).union(CustomSet([2]))) XCTAssertEqual(CustomSet([3.0, 3, 2, 1]), - CustomSet([1, 3]).union(CustomSet([2, 3.0]))) + CustomSet([1, 3]).union(CustomSet([2, 3.0]))) XCTAssertEqual(CustomSet([3, 1]), - CustomSet([1, 3]).union(CustomSet(emptyTypedArray))) + CustomSet([1, 3]).union(CustomSet(emptyTypedArray))) XCTAssertEqual(CustomSet([2]), - CustomSet([2]).union(CustomSet(emptyTypedArray))) + CustomSet([2]).union(CustomSet(emptyTypedArray))) XCTAssertEqual(CustomSet(emptyTypedArray), - CustomSet(emptyTypedArray).union(CustomSet(emptyTypedArray))) + CustomSet(emptyTypedArray).union(CustomSet(emptyTypedArray))) } - - } diff --git a/exercises/difference-of-squares/DifferenceOfSquaresExample.swift b/exercises/difference-of-squares/DifferenceOfSquaresExample.swift index 27b100859..6b4eed828 100644 --- a/exercises/difference-of-squares/DifferenceOfSquaresExample.swift +++ b/exercises/difference-of-squares/DifferenceOfSquaresExample.swift @@ -1,29 +1,25 @@ -// Foundation not needed - - - struct Squares { - + var max = 1 - - init (_ max:Int){ - if max > 0{ + + init (_ max: Int) { + if max > 0 { self.max = max } } - - var squareOfSums:Int{ + + var squareOfSums: Int { let numbers = Array(1...self.max) let sum = numbers.reduce(0, combine: + ) - return sum * sum; + return sum * sum } - - var sumOfSquares:Int{ + + var sumOfSquares: Int { let numbers = Array(1...self.max) - return numbers.map{ return $0*$0 }.reduce(0, combine: + ) + return numbers.map { return $0*$0 }.reduce(0, combine: + ) } - - var differenceOfSquares:Int{ + + var differenceOfSquares: Int { return squareOfSums - sumOfSquares } -} \ No newline at end of file +} diff --git a/exercises/difference-of-squares/DifferenceOfSquaresTest.swift b/exercises/difference-of-squares/DifferenceOfSquaresTest.swift index 49e511544..6752d4db8 100644 --- a/exercises/difference-of-squares/DifferenceOfSquaresTest.swift +++ b/exercises/difference-of-squares/DifferenceOfSquaresTest.swift @@ -1,44 +1,43 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class DifferenceOfSquaresTest: XCTestCase { - + func testSquareOfSumsTo5() { XCTAssertEqual(225, Squares(5).squareOfSums) } - + func testSumOfSquaresTo5() { XCTAssertEqual(55, Squares(5).sumOfSquares) } - + func testDifferenceOfSquaresOfSumsTo5() { XCTAssertEqual(170, Squares(5).differenceOfSquares) } - + func testSquareOfSumsTo10() { XCTAssertEqual(3025, Squares(10).squareOfSums) } - + func testSumOfSquaresTo10() { XCTAssertEqual(385, Squares(10).sumOfSquares) } - + func testDifferenceOfSquaresOfSumsTo10() { XCTAssertEqual(2640, Squares(10).differenceOfSquares) } - + func testSquareOfSumsTo100() { XCTAssertEqual(25_502_500, Squares(100).squareOfSums) } - + func testSumOfSquaresTo100() { XCTAssertEqual(338_350, Squares(100).sumOfSquares) } - + func testDifferenceOfSquaresOfSumsTo100() { XCTAssertEqual(25_164_150, Squares(100).differenceOfSquares) } - -} \ No newline at end of file + +} diff --git a/exercises/dominoes/DominoesExample.swift b/exercises/dominoes/DominoesExample.swift index 4d3f5925b..758e5ceb5 100644 --- a/exercises/dominoes/DominoesExample.swift +++ b/exercises/dominoes/DominoesExample.swift @@ -1,161 +1,151 @@ +struct Dominoes { + let singles: [Bone] + let doubles: [Bone] -struct Dominoes{ - - let singles:[Bone] - let doubles:[Bone] - - var chained:Bool { + var chained: Bool { if singles.isEmpty && doubles.count == 1 {return true } - let (success,result) = chainning(swapDuplicate(singles)) + let (success, result) = chainning(swapDuplicate(singles)) if doubles.isEmpty { return success - } else if success == true{ + } else if success == true { return doubles.count == doubles.filter({each in return result.contains({e in return e.value.head == each.value.head})}).count } else { return false } } - - private func swapDuplicate(input:[Bone])->[Bone]{ + + private func swapDuplicate(_ input: [Bone]) -> [Bone] { var unique = [Bone]() - for each in input{ - if unique.contains(each){ - - #if swift(>=3.0) - unique.insert(Bone(each.value.tail,each.value.head), at: 0) - #else - unique.insert(Bone(each.value.tail,each.value.head), atIndex: 0) - #endif - }else{ + for each in input { + if unique.contains(each) { + unique.insert(Bone(each.value.tail, each.value.head), at: 0) + + } else { unique.append(each) } } return unique } - - private func chainning(input:[Bone])->(Bool,[Bone]){ + + private func chainning(_ input: [Bone]) -> (Bool, [Bone]) { var matched = input - - guard !matched.isEmpty else {return (false,[])} - + + guard !matched.isEmpty else {return (false, [])} + let total = matched.count - 1 - + for index in 0...total { - for innerIndex in 0...total{ + for innerIndex in 0...total { matched[index].connect(matched[innerIndex]) } } return (matched.filter({$0.connected >= 2}).count == matched.count) ? - (true, matched) : (false,[]) + (true, matched) : (false, []) } - - init(_ input: [(Int,Int)]) { + + init(_ input: [(Int, Int)]) { var singles = [Bone]() var doubles = [Bone]() - - for each in input{ + + for each in input { if each.0 == each.1 { - doubles.append(Bone(each.0,each.1)) + doubles.append(Bone(each.0, each.1)) } else { - singles.append(Bone(each.0,each.1)) + singles.append(Bone(each.0, each.1)) } } self.singles = singles self.doubles = doubles } } - - -func ==(lhs: Bone, rhs: Bone) -> Bool { +func == (lhs: Bone, rhs: Bone) -> Bool { return lhs.value.head == rhs.value.head && lhs.value.tail == rhs.value.tail } +class Bone: CustomStringConvertible, Equatable { - -class Bone:CustomStringConvertible,Equatable{ - - let value:(head:Int,tail:Int) - var connected:Int = 0 - var available:Int? - var connectedTo:Bone? - var description:String{ + let value:(head: Int, tail: Int) + var connected: Int = 0 + var available: Int? + var connectedTo: Bone? + var description: String { return "\(value)|\(connected)|\(available) " } - - func connect(input:Bone)->Bool{ - + @discardableResult + func connect(_ input: Bone) -> Bool { + if self === input {return false} if self === input.connectedTo {return false} - + var toReturn = false - + if connected == 1 && input.connected == 0 { - + guard let available = available else { return false } - - if available == input.value.head{ + + if available == input.value.head { self.available = nil input.available = input.value.tail toReturn = true } - - if available == input.value.tail{ + + if available == input.value.tail { self.available = nil input.available = input.value.head toReturn = true } } - + if connected == 0 && input.connected == 1 { - + guard let available = input.available else { return false } - - if available == value.head{ + + if available == value.head { input.available = nil self.available = value.tail toReturn = true } - - if available == value.tail{ + + if available == value.tail { input.available = nil self.available = value.head toReturn = true } - + } - + if connected == 1 && input.connected == 1 { - + if available == input.available { self.available = nil input.available = nil toReturn = true } } - + if connected == 0 && input.connected == 0 { - + if value.head == input.value.head { available = value.tail input.available = input.value.tail connectedTo = input toReturn = true } - + if value.tail == input.value.tail { available = value.head input.available = input.value.head connectedTo = input toReturn = true } - + if value.head == input.value.tail { available = value.tail input.available = input.value.head connectedTo = input toReturn = true } - + if value.tail == input.value.head { available = value.head input.available = input.value.tail @@ -163,7 +153,7 @@ class Bone:CustomStringConvertible,Equatable{ toReturn = true } } - + if toReturn == true { connected += 1 input.connected += 1 @@ -172,10 +162,10 @@ class Bone:CustomStringConvertible,Equatable{ return false } } - - init(_ head:Int, _ tail:Int){ + + init(_ head: Int, _ tail: Int) { self.value.head = head self.value.tail = tail } - -} \ No newline at end of file + +} diff --git a/exercises/dominoes/DominoesTest.swift b/exercises/dominoes/DominoesTest.swift index fcf57e38b..f413c64be 100644 --- a/exercises/dominoes/DominoesTest.swift +++ b/exercises/dominoes/DominoesTest.swift @@ -1,17 +1,19 @@ -import XCTest +#if swift(>=3.0) + import XCTest +#endif class DominoesTest: XCTestCase { - + func testEmptyInputEmptyOutput() { let input = [(Int, Int)]() XCTAssertFalse(Dominoes(input).chained) } - + func testSingletonInputSingletonOutput() { let input = [(1, 1)] XCTAssertTrue(Dominoes(input).chained) } - + func testSingletonThatCantBeChained() { let input = [(1, 2)] XCTAssertFalse(Dominoes(input).chained) @@ -21,45 +23,45 @@ class DominoesTest: XCTestCase { let input = [(1, 2), (3, 1), (2, 3)] XCTAssertTrue(Dominoes(input).chained) } - + func testCanReverseDominoes() { let input = [(1, 2), (1, 3), (2, 3)] XCTAssertTrue(Dominoes(input).chained) } - + func testInvalidInput() { let input = [(1, 2), (4, 1), (2, 3)] XCTAssertFalse(Dominoes(input).chained) } - + func testDisconnectedSimple() { let input = [(1, 1), (2, 2)] XCTAssertFalse(Dominoes(input).chained) } - + func testDisconnectedDoubleLoop() { let input = [(1, 2), (2, 1), (3, 4), (4, 3)] XCTAssertFalse(Dominoes(input).chained) } - + func testDisconnectedSingleIsolated() { let input = [(1, 2), (2, 3), (3, 1), (4, 4)] XCTAssertFalse(Dominoes(input).chained) } - + func testNeedBacktrack() { let input = [(1, 2), (2, 3), (3, 1), (2, 4), (2, 4)] XCTAssertTrue(Dominoes(input).chained) } - + func testSeparateLoops() { let input = [(1, 2), (2, 3), (3, 1), (1, 1), (2, 2), (3, 3)] XCTAssertTrue(Dominoes(input).chained) } - + func testTenElements() { let input = [(1, 2), (5, 3), (3, 1), (1, 2), (2, 4), (1, 6), (2, 3), (3, 4), (5, 6)] XCTAssertTrue(Dominoes(input).chained) } - + } diff --git a/exercises/etl/EtlExample.swift b/exercises/etl/EtlExample.swift index ec805c106..6b026b4f3 100644 --- a/exercises/etl/EtlExample.swift +++ b/exercises/etl/EtlExample.swift @@ -1,16 +1,11 @@ -// Foundation not needed - - - struct ETL { - static func transform(old: [Int: [String] ] ) -> [String: Int] - { + static func transform(_ old: [Int: [String] ] ) -> [String: Int] { var result = [String: Int]() for (score, letters) in old { for letter in letters { - result[letter.lowercaseString] = score + result[letter.lowercased()] = score } } return result } -} \ No newline at end of file +} diff --git a/exercises/etl/EtlTest.swift b/exercises/etl/EtlTest.swift index be2550ee0..600e621a7 100644 --- a/exercises/etl/EtlTest.swift +++ b/exercises/etl/EtlTest.swift @@ -1,6 +1,6 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class EtlTest: XCTestCase { @@ -8,44 +8,44 @@ class EtlTest: XCTestCase { let old = [ 1 : [ "A" ] ] let expected = ["a" : 1 ] let results = ETL.transform(old) - + XCTAssertEqual(results, expected) } - + func testTransformMoreValues() { let old = [ 1 : [ "A", "E", "I", "O", "U" ] ] let expected = ["a" : 1, "e": 1, "i": 1, "o": 1, "u": 1 ] let results = ETL.transform(old) - + XCTAssertEqual(results, expected) } - + func testMoreKeys() { let old = [ 1 : [ "A", "E" ], 2: ["D", "G"] ] let expected = ["a" : 1, "e": 1, "d": 2, "g": 2 ] let results = ETL.transform(old) - + XCTAssertEqual(results, expected) } - + func testFullDataSet() { let old = [ 1 : [ "A", "E", "I", "O", "U", "L", "N", "R", "S", "T" ], - 2 : [ "D", "G" ], - 3 : [ "B", "C", "M", "P" ], - 4 : [ "F", "H", "V", "W", "Y" ], - 5 : [ "K"], - 8 : [ "J", "X" ], - 10 : [ "Q", "Z" ] + 2 : [ "D", "G" ], + 3 : [ "B", "C", "M", "P" ], + 4 : [ "F", "H", "V", "W", "Y" ], + 5 : [ "K"], + 8 : [ "J", "X" ], + 10 : [ "Q", "Z" ] ] let expected = [ "a" : 1, "b" : 3, "c" : 3, "d" : 2, "e" : 1, - "f" : 4, "g" : 2, "h" : 4, "i" : 1, "j" : 8, - "k" : 5, "l" : 1, "m" : 3, "n" : 1, "o" : 1, - "p" : 3, "q" : 10, "r" : 1, "s" : 1, "t" : 1, - "u" : 1, "v" : 4, "w" : 4, "x" : 8, "y" : 4, - "z" : 10 ] - + "f" : 4, "g" : 2, "h" : 4, "i" : 1, "j" : 8, + "k" : 5, "l" : 1, "m" : 3, "n" : 1, "o" : 1, + "p" : 3, "q" : 10, "r" : 1, "s" : 1, "t" : 1, + "u" : 1, "v" : 4, "w" : 4, "x" : 8, "y" : 4, + "z" : 10 ] + let results = ETL.transform(old) - + XCTAssertEqual(results, expected) } -} \ No newline at end of file +} diff --git a/exercises/food-chain/FoodChainExample.swift b/exercises/food-chain/FoodChainExample.swift index c37081b10..01a84ae52 100644 --- a/exercises/food-chain/FoodChainExample.swift +++ b/exercises/food-chain/FoodChainExample.swift @@ -1,27 +1,19 @@ -// Foundation not needed - - - struct FoodChain { - + private static let animals = ["fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"] - + static func song() -> String { let verses = (1...8).map { verse($0) } - #if swift(>=3.0) return verses.joined(separator: "\n\n") - #else - return verses.joinWithSeparator("\n\n") - #endif } - - static func verse(number: Int) -> String { + + static func verse(_ number: Int) -> String { var result = "" - + var index = number - 1 let animal = animals[index] result += "I know an old lady who swallowed a \(animal).\n" - + switch number { case 2: result += "It wriggled and jiggled and tickled inside her.\n" case 3: result += "How absurd to swallow a bird!\n" @@ -32,7 +24,7 @@ struct FoodChain { case 8: result += "She's dead, of course!"; return result default: break } - + while index >= 1 { result += "She swallowed the \(animals[index]) to catch the \(animals[index - 1])" if index == 2 { @@ -42,8 +34,8 @@ struct FoodChain { index -= 1 } result += "I don't know why she swallowed the fly. Perhaps she'll die." - + return result } - + } diff --git a/exercises/food-chain/FoodChainTest.swift b/exercises/food-chain/FoodChainTest.swift index 7b6a30979..58a8b967d 100644 --- a/exercises/food-chain/FoodChainTest.swift +++ b/exercises/food-chain/FoodChainTest.swift @@ -1,112 +1,112 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class FoodChainTest: XCTestCase { - + func testVerse1() { let expected = "I know an old lady who swallowed a fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die." + "I don't know why she swallowed the fly. Perhaps she'll die." XCTAssertEqual(expected, FoodChain.verse(1)) } - + func testVerse2() { let expected = "I know an old lady who swallowed a spider.\n" + - "It wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die." + "It wriggled and jiggled and tickled inside her.\n" + + "She swallowed the spider to catch the fly.\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." XCTAssertEqual(expected, FoodChain.verse(2)) } - + func testVerse5() { let expected = "I know an old lady who swallowed a dog.\n" + - "What a hog, to swallow a dog!\n" + - "She swallowed the dog to catch the cat.\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die." + "What a hog, to swallow a dog!\n" + + "She swallowed the dog to catch the cat.\n" + + "She swallowed the cat to catch the bird.\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + + "She swallowed the spider to catch the fly.\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." XCTAssertEqual(expected, FoodChain.verse(5)) } - + func testVerse7() { let expected = "I know an old lady who swallowed a cow.\n" + - "I don't know how she swallowed a cow!\n" + - "She swallowed the cow to catch the goat.\n" + - "She swallowed the goat to catch the dog.\n" + - "She swallowed the dog to catch the cat.\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die." + "I don't know how she swallowed a cow!\n" + + "She swallowed the cow to catch the goat.\n" + + "She swallowed the goat to catch the dog.\n" + + "She swallowed the dog to catch the cat.\n" + + "She swallowed the cat to catch the bird.\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + + "She swallowed the spider to catch the fly.\n" + + "I don't know why she swallowed the fly. Perhaps she'll die." XCTAssertEqual(expected, FoodChain.verse(7)) } - + func testVerse8() { let expected = "I know an old lady who swallowed a horse.\n" + - "She's dead, of course!" + "She's dead, of course!" XCTAssertEqual(expected, FoodChain.verse(8)) } - + func testWholeSong() { let expected = "I know an old lady who swallowed a fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - - "I know an old lady who swallowed a spider.\n" + - "It wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - - "I know an old lady who swallowed a bird.\n" + - "How absurd to swallow a bird!\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - - "I know an old lady who swallowed a cat.\n" + - "Imagine that, to swallow a cat!\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - - "I know an old lady who swallowed a dog.\n" + - "What a hog, to swallow a dog!\n" + - "She swallowed the dog to catch the cat.\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - - "I know an old lady who swallowed a goat.\n" + - "Just opened her throat and swallowed a goat!\n" + - "She swallowed the goat to catch the dog.\n" + - "She swallowed the dog to catch the cat.\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - - "I know an old lady who swallowed a cow.\n" + - "I don't know how she swallowed a cow!\n" + - "She swallowed the cow to catch the goat.\n" + - "She swallowed the goat to catch the dog.\n" + - "She swallowed the dog to catch the cat.\n" + - "She swallowed the cat to catch the bird.\n" + - "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + - "She swallowed the spider to catch the fly.\n" + - "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - - "I know an old lady who swallowed a horse.\n" + - "She's dead, of course!" + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + + + "I know an old lady who swallowed a spider.\n" + + "It wriggled and jiggled and tickled inside her.\n" + + "She swallowed the spider to catch the fly.\n" + + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + + + "I know an old lady who swallowed a bird.\n" + + "How absurd to swallow a bird!\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + + "She swallowed the spider to catch the fly.\n" + + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + + + "I know an old lady who swallowed a cat.\n" + + "Imagine that, to swallow a cat!\n" + + "She swallowed the cat to catch the bird.\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + + "She swallowed the spider to catch the fly.\n" + + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + + + "I know an old lady who swallowed a dog.\n" + + "What a hog, to swallow a dog!\n" + + "She swallowed the dog to catch the cat.\n" + + "She swallowed the cat to catch the bird.\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + + "She swallowed the spider to catch the fly.\n" + + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + + + "I know an old lady who swallowed a goat.\n" + + "Just opened her throat and swallowed a goat!\n" + + "She swallowed the goat to catch the dog.\n" + + "She swallowed the dog to catch the cat.\n" + + "She swallowed the cat to catch the bird.\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + + "She swallowed the spider to catch the fly.\n" + + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + + + "I know an old lady who swallowed a cow.\n" + + "I don't know how she swallowed a cow!\n" + + "She swallowed the cow to catch the goat.\n" + + "She swallowed the goat to catch the dog.\n" + + "She swallowed the dog to catch the cat.\n" + + "She swallowed the cat to catch the bird.\n" + + "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + + "She swallowed the spider to catch the fly.\n" + + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + + + "I know an old lady who swallowed a horse.\n" + + "She's dead, of course!" XCTAssertEqual(expected, FoodChain.song()) } - + } diff --git a/exercises/gigasecond/GigasecondExample.swift b/exercises/gigasecond/GigasecondExample.swift index 72a672371..524c14317 100644 --- a/exercises/gigasecond/GigasecondExample.swift +++ b/exercises/gigasecond/GigasecondExample.swift @@ -1,20 +1,18 @@ import Darwin +private extension tm { + var year: Int32 { return tm_year + 1900 } -private extension tm{ - - var year:Int32 { return tm_year + 1900 } - - var month:Int32 { return tm_mon + 1 } - - var day:Int32 { return tm_mday } - - var time:(hour:Int32, mins:Int32, secs:Int32){ + var month: Int32 { return tm_mon + 1 } + + var day: Int32 { return tm_mday } + + var time:(hour: Int32, mins: Int32, secs: Int32) { return (hour: tm_hour, mins: tm_min, secs:tm_sec) } - - init(year:Int32, month:Int32, day:Int32, hour:Int32 = 0, mins:Int32 = 0, secs:Int32 = 0){ + + init(year: Int32, month: Int32, day: Int32, hour: Int32 = 0, mins: Int32 = 0, secs: Int32 = 0) { self.init() self.tm_year = year - 1900 self.tm_mon = month - 1 @@ -22,17 +20,17 @@ private extension tm{ self.tm_hour = hour self.tm_min = mins self.tm_sec = secs - + } - - mutating func dateByAddingSeconds(seconds:Int) -> tm { + + mutating func dateByAddingSeconds(_ seconds: Int) -> tm { var d1 = timegm(&self) + seconds - return gmtime(&d1).memory + return gmtime(&d1).pointee } - - private func addLeadingZero(input:Int32) -> String{ + + private func addLeadingZero(_ input: Int32) -> String { var addZero = false - (0...9).forEach{ + (0...9).forEach { if $0 == Int(input) { addZero = true } @@ -40,14 +38,14 @@ private extension tm{ if addZero { return "0\(input)" } else {return String(input)} - + } - - var description:String { - - let date = [year, month, day, time.hour, time.mins, time.secs].map{addLeadingZero($0)} - - return date[0] + "-" + date[1] + "-" + date[2] + "T" + date[3] + ":" + date[4] + ":" + date[5] + + var description: String { + + let date = [year, month, day, time.hour, time.mins, time.secs].map {addLeadingZero($0)} + + return date[0] + "-" + date[1] + "-" + date[2] + "T" + date[3] + ":" + date[4] + ":" + date[5] } } @@ -58,14 +56,12 @@ func == (lhs: Gigasecond, rhs: Gigasecond) -> Bool { func == (lhs: String, rhs: Gigasecond) -> Bool { return lhs == rhs.description } +struct Gigasecond: Equatable, CustomStringConvertible { + private var startDate: tm! + private var gigasecondDate: tm! -struct Gigasecond: Equatable, CustomStringConvertible{ - - private var startDate:tm! - private var gigasecondDate:tm! - - init?(from:String){ + init?(from: String) { if let result = parse(from) { var start = result self.startDate = start @@ -74,31 +70,27 @@ struct Gigasecond: Equatable, CustomStringConvertible{ return nil } } - - - private func parse(input:String) -> tm? { - - let dateTime = input.characters.split("T").map{String($0)} + private func parse(_ input: String) -> tm? { + + let dateTime = input.characters.split(separator: "T").map {String($0)} if dateTime.count > 1 { - let date = dateTime[0].characters.split("-").map{String($0)} - let time = dateTime[1].characters.split(":").map{String($0)} + let date = dateTime[0].characters.split(separator: "-").map {String($0)} + let time = dateTime[1].characters.split(separator: ":").map {String($0)} if date.count == 3 && time.count == date.count { - + let year = Int32(date[0]) ?? 0 let month = Int32(date[1]) ?? 0 let day = Int32(date[2]) ?? 0 let hour = Int32(time[0]) ?? 0 let minute = Int32(time[1]) ?? 0 let second = Int32(time[2]) ?? 0 - + return tm(year: year, month: month, day: day, hour: hour, mins: minute, secs: second) } } return nil } - var description:String { + var description: String { return gigasecondDate.description } - - -} \ No newline at end of file +} diff --git a/exercises/gigasecond/GigasecondTest.swift b/exercises/gigasecond/GigasecondTest.swift index 09303848c..b9f800a7a 100644 --- a/exercises/gigasecond/GigasecondTest.swift +++ b/exercises/gigasecond/GigasecondTest.swift @@ -1,35 +1,36 @@ -import XCTest +#if swift(>=3.0) + import XCTest +#endif class GigasecondTest: XCTestCase { - + func test1 () { let gs = Gigasecond(from: "2011-04-25T00:00:00")?.description - XCTAssertEqual("2043-01-01T01:46:40", gs) + XCTAssertEqual("2043-01-01T01:46:40", gs) } - + func test2 () { let gs = Gigasecond(from: "1977-06-13T00:00:00")?.description - XCTAssertEqual("2009-02-19T01:46:40", gs) + XCTAssertEqual("2009-02-19T01:46:40", gs) } - + func test3 () { let gs = Gigasecond(from: "1959-07-19T00:00:00")?.description - XCTAssertEqual("1991-03-27T01:46:40", gs) + XCTAssertEqual("1991-03-27T01:46:40", gs) } - + func testTimeWithSeconds () { let gs = Gigasecond(from: "1959-07-19T23:59:59")?.description XCTAssertEqual("1991-03-28T01:46:39", gs) } - + func testFullTimeSpecified () { let gs = Gigasecond(from: "2015-01-24T22:00:00")?.description XCTAssertEqual("2046-10-02T23:46:40", gs) } - + func testFullTimeWithDayRollOver () { let gs = Gigasecond(from: "2015-01-24T23:59:59")?.description XCTAssertEqual("2046-10-03T01:46:39", gs) } - } - +} diff --git a/exercises/grade-school/GradeSchoolExample.swift b/exercises/grade-school/GradeSchoolExample.swift index 7b9ff37bc..f9cdbfeeb 100644 --- a/exercises/grade-school/GradeSchoolExample.swift +++ b/exercises/grade-school/GradeSchoolExample.swift @@ -1,12 +1,7 @@ -// Foundation not needed - - - - struct GradeSchool { var roster = [Int: Set]() - - mutating func addStudent(name: String, grade: Int) { + + mutating func addStudent(_ name: String, grade: Int) { if let students = roster[grade] { var students = students students.insert(name) @@ -15,19 +10,16 @@ struct GradeSchool { roster[grade] = Set(arrayLiteral: name) } } - - func studentsInGrade(grade: Int) -> Set { + + func studentsInGrade(_ grade: Int) -> Set { return roster[grade] ?? Set() } - + var sortedRoster: [Int: Set] { var sortedRoster = [Int: Set](minimumCapacity: roster.count) for (grade, students) in roster { - #if swift(>=3.0) sortedRoster[grade] = Set(students.sorted()) - #else - sortedRoster[grade] = Set(students.sort()) - #endif + } return sortedRoster } diff --git a/exercises/grade-school/GradeSchoolTest.swift b/exercises/grade-school/GradeSchoolTest.swift index f23c8729d..ba853ce8e 100644 --- a/exercises/grade-school/GradeSchoolTest.swift +++ b/exercises/grade-school/GradeSchoolTest.swift @@ -1,51 +1,38 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif private extension XCTestCase { - + // Workaround unit test liminitaiton on Optional Arrays/Sets - #if swift(>=3.0) - private func sameCollection(result: C?, _ expected: [String]?) -> Bool { + private func sameCollection(_ result: C?, _ expected: [String]?) -> Bool { guard let result = result, expected = expected where similar(result, expected) else { return false } for (index, student) in result.enumerated() { guard index < expected.count && expected.contains(student) else { return false } } return true } - #else // Swift 2.2 and below - private func sameCollection(result: C?, _ expected: [String]?) -> Bool { - guard let result = result, expected = expected where similar(result, expected) else { return false } - for (index, student) in result.enumerate() { - guard index < expected.count && expected.contains(student) else { return false } - } - return true - } - #endif - - private func similar(result: C, _ expected: [String]) -> Bool { + private func similar(_ result: C, _ expected: [String]) -> Bool { return result.count.toIntMax() == IntMax(expected.count) } - - func XCTAssertEqualCollection (collectionS : Set? , _ collectionA : [String]? ) { + + func XCTAssertEqualCollection (_ collectionS: Set?, _ collectionA: [String]? ) { XCTAssert(sameCollection(collectionS, collectionA)) } - - func XCTAssertEqualCollection (collectionA1 : [String]?, _ collectionA2 : [String]? ) { + + func XCTAssertEqualCollection (_ collectionA1: [String]?, _ collectionA2: [String]? ) { XCTAssert(sameCollection(collectionA1, collectionA2)) } } - - class GradeSchoolTest: XCTestCase { - + func testAnEmptySchool() { let school = GradeSchool() let result = school.roster XCTAssertTrue(result.isEmpty) - + } - + func testAddStudent() { var school = GradeSchool() school.addStudent("Aimee", grade: 2) @@ -54,7 +41,7 @@ class GradeSchoolTest: XCTestCase { XCTAssertEqual(Array(result.keys), Array(expected.keys)) XCTAssertEqualCollection(result[2], expected[2]) } - + func testAddMoreStudentsInSameClass() { var school = GradeSchool() school.addStudent("Fred", grade: 2) @@ -65,22 +52,18 @@ class GradeSchoolTest: XCTestCase { XCTAssertEqual(Array(result.keys), Array(expected.keys)) XCTAssertEqualCollection(result[2], expected[2]) } - + func testAddStudentsToDifferentGrades() { var school = GradeSchool() school.addStudent("Chelsea", grade:3) school.addStudent("Logan", grade: 7) let result = school.roster let expected = [3: ["Chelsea"], 7: ["Logan"]] - - #if swift(>=3.0) - XCTAssertEqual(Array(result.keys).sorted(isOrderedBefore: >), Array(expected.keys).sorted(isOrderedBefore: >)) - #else - XCTAssertEqual(Array(result.keys).sort(>), Array(expected.keys).sort(>)) - #endif + XCTAssertEqual(Array(result.keys).sorted(isOrderedBefore: >), Array(expected.keys).sorted(isOrderedBefore: >)) + XCTAssertEqualCollection(result[3], expected[3]) } - + func testGetStudentsInAGrade() { var school = GradeSchool() school.addStudent("Franklin", grade: 5) @@ -90,15 +73,15 @@ class GradeSchoolTest: XCTestCase { let expected = ["Franklin", "Bradley"] XCTAssertEqualCollection(result, expected) } - + func testGetStudentsInANonExistantGrade() { let school = GradeSchool() let result = school.studentsInGrade(1) - + let expected = [String]() XCTAssertEqualCollection(result, expected) } - + func testSortSchool() { var school = GradeSchool() school.addStudent("Jennifer", grade: 4) @@ -106,20 +89,17 @@ class GradeSchoolTest: XCTestCase { school.addStudent("Christopher", grade: 4) school.addStudent("Kyle", grade: 3) let result = school.sortedRoster - + let expected = [ - 3 : ["Kyle"], - 4 : ["Christopher", "Jennifer"], - 6 : ["Kareem"] + 3 : ["Kyle"], + 4 : ["Christopher", "Jennifer"], + 6 : ["Kareem"] ] - #if swift(>=3.0) - XCTAssertEqual(Array(result.keys).sorted(isOrderedBefore: >), Array(expected.keys).sorted(isOrderedBefore: >)) - #else - XCTAssertEqual(Array(result.keys).sort(>), Array(expected.keys).sort(>)) - #endif + XCTAssertEqual(Array(result.keys).sorted(isOrderedBefore: >), Array(expected.keys).sorted(isOrderedBefore: >)) + XCTAssertEqualCollection(result[3], expected[3]) XCTAssertEqualCollection(result[4], expected[4]) XCTAssertEqualCollection(result[6], expected[6]) } - + } diff --git a/exercises/grains/GrainsExample.swift b/exercises/grains/GrainsExample.swift index 836626130..57e05f354 100644 --- a/exercises/grains/GrainsExample.swift +++ b/exercises/grains/GrainsExample.swift @@ -1,34 +1,31 @@ import Darwin - - - struct Grains { - - enum Error: ErrorType { + + enum Error: ErrorProtocol { case inputTooLow(String) case inputTooHigh(String) } - static func square(num: Int) throws -> UInt64 { + static func square(_ num: Int) throws -> UInt64 { guard num >= 1 else { let message = "Input[\(num)] invalid. Input should be between 1 and 64 (inclusive)" throw Error.inputTooLow(message) } - + guard num <= 64 else { let message = "Input[\(num)] invalid. Input should be between 1 and 64 (inclusive)" throw Error.inputTooHigh(message) } - + let one: UInt64 = 1 let shift = UInt64(num - 1) return one << shift } - - static var total:UInt64 { + + static var total: UInt64 { let numbers = (1...64).map { $0 } - + return numbers.reduce(UInt64(0)) { let squared = try! square($1) return $0 + squared diff --git a/exercises/grains/GrainsTest.swift b/exercises/grains/GrainsTest.swift index e32e6c411..925e7e181 100644 --- a/exercises/grains/GrainsTest.swift +++ b/exercises/grains/GrainsTest.swift @@ -1,18 +1,16 @@ - -import XCTest - - - +#if swift(>=3.0) + import XCTest +#endif class GrainsTest: XCTestCase { - + func testInvalidInput1() { var throwsInputTooHighError = false - + defer { XCTAssertTrue(throwsInputTooHighError) } - + do { let _ = try Grains.square(65) } catch Grains.Error.inputTooHigh(let message) { @@ -21,16 +19,16 @@ class GrainsTest: XCTestCase { } catch { return } - + } - + func testInvalidInput2() { var throwsInputTooLowError = false - + defer { XCTAssertTrue(throwsInputTooLowError) } - + do { let _ = try Grains.square(0) } catch Grains.Error.inputTooLow(let message) { @@ -40,14 +38,14 @@ class GrainsTest: XCTestCase { return } } - + func testInvalidInput3() { var throwsInputTooLowError = false - + defer { XCTAssertTrue(throwsInputTooLowError) } - + do { let _ = try Grains.square(-1) } catch Grains.Error.inputTooLow(let message) { @@ -57,11 +55,11 @@ class GrainsTest: XCTestCase { return } } - + func testSquare1() { XCTAssertEqual(try! Grains.square(1), 1) } - + func testSquare2() { XCTAssertEqual(try! Grains.square(2), 2) } @@ -85,7 +83,7 @@ class GrainsTest: XCTestCase { func testSquare64() { XCTAssertEqual(try! Grains.square(64), 9_223_372_036_854_775_808) } - + func testTotalGrains() { XCTAssertEqual(Grains.total, 18_446_744_073_709_551_615) } diff --git a/exercises/hamming/HammingExample.swift b/exercises/hamming/HammingExample.swift index a488057d8..9497e3176 100644 --- a/exercises/hamming/HammingExample.swift +++ b/exercises/hamming/HammingExample.swift @@ -1,14 +1,10 @@ -// Foundation not needed - - - struct Hamming { - static func compute(input: String, against: String) -> Int? { + static func compute(_ input: String, against: String) -> Int? { var differences = 0 - + let char1 = convertStringToArray(input) let char2 = convertStringToArray(against) - + if char1.count != char2.count { return nil } for i in 0.. [Character] { +private func convertStringToArray(_ input: String) -> [Character] { var characterArray: [Character] = [] - + for character in input.characters { characterArray.append(character) } - + return characterArray } diff --git a/exercises/hamming/HammingTest.swift b/exercises/hamming/HammingTest.swift index 476f1b3ae..431ce9637 100644 --- a/exercises/hamming/HammingTest.swift +++ b/exercises/hamming/HammingTest.swift @@ -1,6 +1,6 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class HammingTest: XCTestCase { func testNoDifferenceBetweenEmptyStrands() { @@ -8,36 +8,36 @@ class HammingTest: XCTestCase { let expected = 0 XCTAssertEqual(expected, result) } - + func testNoDifferenceBetweenIdenticalStrands() { let result = Hamming.compute("GGACTGA", against:"GGACTGA")! let expected = 0 - XCTAssertEqual(expected,result) + XCTAssertEqual(expected, result) } - + func testCompleteHammingDistanceInSmallStrand() { let result = Hamming.compute("ACT", against: "GGA")! let expected = 3 - XCTAssertEqual(expected,result) + XCTAssertEqual(expected, result) } - + func testSmallHammingDistanceInMiddleSomewhere() { let result = Hamming.compute("GGACG", against:"GGTCG")! let expected = 1 - XCTAssertEqual(expected,result) + XCTAssertEqual(expected, result) } - + func testLargerDistance() { let result = Hamming.compute("ACCAGGG", against:"ACTATGG")! let expected = 2 - XCTAssertEqual(expected,result) + XCTAssertEqual(expected, result) } - + func testReturnsNilWhenOtherStrandLonger() { let result = Hamming.compute("AAACTAGGGG", against:"AGGCTAGCGGTAGGAC") XCTAssertNil(result, "Different length strands return nil") } - + func testReturnsNilWhenOriginalStrandLonger() { let result = Hamming.compute("GACTACGGACAGGGTAGGGAAT", against:"GACATCGCACACC") XCTAssertNil(result, "Different length strands return nil") diff --git a/exercises/hello-world/helloWorld.swift b/exercises/hello-world/helloWorld.swift index d8aec73bc..ff42492bc 100644 --- a/exercises/hello-world/helloWorld.swift +++ b/exercises/hello-world/helloWorld.swift @@ -1,3 +1 @@ - - -// Enter Solution Here \ No newline at end of file +// Enter Solution Here diff --git a/exercises/hello-world/helloWorld.xcodeproj/project.pbxproj b/exercises/hello-world/helloWorld.xcodeproj/project.pbxproj index a8aa09d4e..06b585f37 100644 --- a/exercises/hello-world/helloWorld.xcodeproj/project.pbxproj +++ b/exercises/hello-world/helloWorld.xcodeproj/project.pbxproj @@ -8,12 +8,12 @@ /* Begin PBXBuildFile section */ 9DCE80801BA747050024C69D /* helloWorldTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DCE807F1BA747050024C69D /* helloWorldTest.swift */; }; - 9DCE80881BA748820024C69D /* helloWorld.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DCE80871BA748820024C69D /* helloWorld.swift */; settings = {ASSET_TAGS = (); }; }; + 9DCE80881BA748820024C69D /* helloWorld.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DCE80871BA748820024C69D /* helloWorld.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 9DCE807D1BA747050024C69D /* helloWorldTest.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = helloWorldTest.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 9DCE807F1BA747050024C69D /* helloWorldTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = helloWorldTest.swift; sourceTree = ""; }; + 9DCE807F1BA747050024C69D /* helloWorldTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = helloWorldTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 9DCE80811BA747050024C69D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 9DCE80871BA748820024C69D /* helloWorld.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = helloWorld.swift; sourceTree = SOURCE_ROOT; }; /* End PBXFileReference section */ diff --git a/exercises/hello-world/helloWorldExample.swift b/exercises/hello-world/helloWorldExample.swift index 2f8534240..b228f627f 100644 --- a/exercises/hello-world/helloWorldExample.swift +++ b/exercises/hello-world/helloWorldExample.swift @@ -1,7 +1,5 @@ - - struct HelloWorld { - static func hello(text:String = "World") -> String{ + static func hello(_ text: String = "World") -> String { return "Hello, \(text)!" } -} \ No newline at end of file +} diff --git a/exercises/hello-world/helloWorldTest/helloWorldTest.swift b/exercises/hello-world/helloWorldTest/helloWorldTest.swift index 442e1bd55..8733c7475 100644 --- a/exercises/hello-world/helloWorldTest/helloWorldTest.swift +++ b/exercises/hello-world/helloWorldTest/helloWorldTest.swift @@ -1,27 +1,27 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class HelloWorldTest: XCTestCase { - - func testNoName(){ + + func testNoName() { let expected = "Hello, World!" XCTAssertEqual(HelloWorld.hello(), expected, "When given no name, we should greet the world!") } - - func testSampleName(){ + + func testSampleName() { let expected = "Hello, Alice!" XCTAssertEqual(HelloWorld.hello("Alice"), expected, "When given 'Alice' we should greet Alice!") } - - func testOtherSampleName(){ + + func testOtherSampleName() { let expected = "Hello, Bob!" XCTAssertEqual(HelloWorld.hello("Bob"), expected, "When given 'Bob' we should greet Bob!") } - - func testNoStrangeName(){ + + func testNoStrangeName() { let expected = "Hello, !" XCTAssertEqual(HelloWorld.hello(""), expected, "When given an empty string, it is strange, but should have a space and punctuation") } - -} \ No newline at end of file + +} diff --git a/exercises/hexadecimal/HexadecimalExample.swift b/exercises/hexadecimal/HexadecimalExample.swift index 3688ed38c..48886ffcc 100644 --- a/exercises/hexadecimal/HexadecimalExample.swift +++ b/exercises/hexadecimal/HexadecimalExample.swift @@ -1,12 +1,8 @@ -// Foundation not needed - - - struct Hexadecimal { - + let hexString: String let intValue: Int? - + private static let hexDigits = [ "0" : 0, "1" : 1, @@ -25,40 +21,40 @@ struct Hexadecimal { "e" : 14, "f" : 15 ] - + init(_ hexString: String) { self.hexString = hexString self.intValue = Hexadecimal.getIntFromHexString(hexString) } - - private static func getIntFromHexString(hexString: String) -> Int? { + + private static func getIntFromHexString(_ hexString: String) -> Int? { var result = 0 var multiplier = 1 - - let digits = hexString.characters.map { String($0).lowercaseString }.reverse() - + + let digits = hexString.characters.map { String($0).lowercased() }.reversed() + for digit in digits { guard let intValue = hexDigits[digit] else { // Invalid hex string return nil } - + result += intValue * multiplier multiplier *= 16 } - + return result } } extension Int { - + init?(_ hex: Hexadecimal) { guard let intValue = hex.intValue else { return nil } - + self = intValue } - -} \ No newline at end of file + +} diff --git a/exercises/hexadecimal/HexadecimalTest.swift b/exercises/hexadecimal/HexadecimalTest.swift index a671e0ca4..288dfa5bd 100644 --- a/exercises/hexadecimal/HexadecimalTest.swift +++ b/exercises/hexadecimal/HexadecimalTest.swift @@ -1,47 +1,47 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class HexadecimalTest: XCTestCase { - + func testHex1IsDecimal1() { XCTAssertEqual(1, Int(Hexadecimal("1"))) } - + func testHexCIsDecimal12() { XCTAssertEqual(12, Int(Hexadecimal("c"))) } - + func testHex10IsDecimal16() { XCTAssertEqual(16, Int(Hexadecimal("10"))) } - + func testHexAFIsDecimal175() { XCTAssertEqual(175, Int(Hexadecimal("af"))) } - + func testHex100IsDecimal256() { XCTAssertEqual(256, Int(Hexadecimal("100"))) } - + func testHex19aceIsDecimal105166() { XCTAssertEqual(105_166, Int(Hexadecimal("19ace"))) } - + func testInvalidHexIsNil() { XCTAssertNil(Int(Hexadecimal("carrot"))) } - + func testBlack() { XCTAssertEqual(0, Int(Hexadecimal("000000"))) } - + func testWhite() { XCTAssertEqual(16_777_215, Int(Hexadecimal("ffffff"))) } - + func testYellow() { XCTAssertEqual(16_776_960, Int(Hexadecimal("ffff00"))) } - -} \ No newline at end of file + +} diff --git a/exercises/house/HouseExample.swift b/exercises/house/HouseExample.swift index 96da211aa..91a2f7f55 100644 --- a/exercises/house/HouseExample.swift +++ b/exercises/house/HouseExample.swift @@ -1,9 +1,5 @@ -// Foundation not needed - - - struct House { - + private static let pieces = [ ["the horse and the hound and the horn", "that belonged to"], ["the farmer sowing his corn", "that kept"], @@ -18,26 +14,19 @@ struct House { ["the malt", "that lay in"], ["the house that Jack built"] ] - + static func recite() -> String { - #if swift(>=3.0) return (1...pieces.count).map { line($0) }.joined(separator: "\n\n") - #else - return (1...pieces.count).map { line($0) }.joinWithSeparator("\n\n") - #endif + } - - private static func line(number: Int) -> String { + + private static func line(_ number: Int) -> String { let startIndex = pieces.count - number let endIndex = pieces.count let selectedPieces = pieces[startIndex ..< endIndex] - #if swift(>=3.0) let text = selectedPieces.map { $0.joined(separator: "\n") }.joined(separator: " ") - #else - let text = selectedPieces.map { $0.joinWithSeparator("\n") }.joinWithSeparator(" ") - #endif + return "This is \(text)." } - -} +} diff --git a/exercises/house/HouseTest.swift b/exercises/house/HouseTest.swift index 5c1d0b811..e6fcedca5 100644 --- a/exercises/house/HouseTest.swift +++ b/exercises/house/HouseTest.swift @@ -1,103 +1,101 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class HouseTest: XCTestCase { - + func testRhyme() { let expected = "This is the house that Jack built.\n\n" + - - "This is the malt\n" + - "that lay in the house that Jack built.\n\n" + - - "This is the rat\n" + - "that ate the malt\n" + - "that lay in the house that Jack built.\n\n" + - - "This is the cat\n" + - "that killed the rat\n" + - "that ate the malt\n" + - "that lay in the house that Jack built.\n\n" + - - "This is the dog\n" + - "that worried the cat\n" + - "that killed the rat\n" + - "that ate the malt\n" + - "that lay in the house that Jack built.\n\n" + - - "This is the cow with the crumpled horn\n" + - "that tossed the dog\n" + - "that worried the cat\n" + - "that killed the rat\n" + - "that ate the malt\n" + - "that lay in the house that Jack built.\n\n" + - - "This is the maiden all forlorn\n" + - "that milked the cow with the crumpled horn\n" + - "that tossed the dog\n" + - "that worried the cat\n" + - "that killed the rat\n" + - "that ate the malt\n" + - "that lay in the house that Jack built.\n\n" + - "This is the man all tattered and torn\n" + - "that kissed the maiden all forlorn\n" + - "that milked the cow with the crumpled horn\n" + - "that tossed the dog\n" + - "that worried the cat\n" + - "that killed the rat\n" + - "that ate the malt\n" + - "that lay in the house that Jack built.\n\n" + - - "This is the priest all shaven and shorn\n" + - "that married the man all tattered and torn\n" + - "that kissed the maiden all forlorn\n" + - "that milked the cow with the crumpled horn\n" + - "that tossed the dog\n" + - "that worried the cat\n" + - "that killed the rat\n" + - "that ate the malt\n" + - "that lay in the house that Jack built.\n\n" + - - "This is the rooster that crowed in the morn\n" + - "that woke the priest all shaven and shorn\n" + - "that married the man all tattered and torn\n" + - "that kissed the maiden all forlorn\n" + - "that milked the cow with the crumpled horn\n" + - "that tossed the dog\n" + - "that worried the cat\n" + - "that killed the rat\n" + - "that ate the malt\n" + - "that lay in the house that Jack built.\n\n" + - - "This is the farmer sowing his corn\n" + - "that kept the rooster that crowed in the morn\n" + - "that woke the priest all shaven and shorn\n" + - "that married the man all tattered and torn\n" + - "that kissed the maiden all forlorn\n" + - "that milked the cow with the crumpled horn\n" + - "that tossed the dog\n" + - "that worried the cat\n" + - "that killed the rat\n" + - "that ate the malt\n" + - "that lay in the house that Jack built.\n\n" + - - "This is the horse and the hound and the horn\n" + - "that belonged to the farmer sowing his corn\n" + - "that kept the rooster that crowed in the morn\n" + - "that woke the priest all shaven and shorn\n" + - "that married the man all tattered and torn\n" + - "that kissed the maiden all forlorn\n" + - "that milked the cow with the crumpled horn\n" + - "that tossed the dog\n" + - "that worried the cat\n" + - "that killed the rat\n" + - "that ate the malt\n" + - "that lay in the house that Jack built." - + "This is the malt\n" + + "that lay in the house that Jack built.\n\n" + + + "This is the rat\n" + + "that ate the malt\n" + + "that lay in the house that Jack built.\n\n" + + + "This is the cat\n" + + "that killed the rat\n" + + "that ate the malt\n" + + "that lay in the house that Jack built.\n\n" + + + "This is the dog\n" + + "that worried the cat\n" + + "that killed the rat\n" + + "that ate the malt\n" + + "that lay in the house that Jack built.\n\n" + + + "This is the cow with the crumpled horn\n" + + "that tossed the dog\n" + + "that worried the cat\n" + + "that killed the rat\n" + + "that ate the malt\n" + + "that lay in the house that Jack built.\n\n" + + + "This is the maiden all forlorn\n" + + "that milked the cow with the crumpled horn\n" + + "that tossed the dog\n" + + "that worried the cat\n" + + "that killed the rat\n" + + "that ate the malt\n" + + "that lay in the house that Jack built.\n\n" + + + "This is the man all tattered and torn\n" + + "that kissed the maiden all forlorn\n" + + "that milked the cow with the crumpled horn\n" + + "that tossed the dog\n" + + "that worried the cat\n" + + "that killed the rat\n" + + "that ate the malt\n" + + "that lay in the house that Jack built.\n\n" + + + "This is the priest all shaven and shorn\n" + + "that married the man all tattered and torn\n" + + "that kissed the maiden all forlorn\n" + + "that milked the cow with the crumpled horn\n" + + "that tossed the dog\n" + + "that worried the cat\n" + + "that killed the rat\n" + + "that ate the malt\n" + + "that lay in the house that Jack built.\n\n" + + + "This is the rooster that crowed in the morn\n" + + "that woke the priest all shaven and shorn\n" + + "that married the man all tattered and torn\n" + + "that kissed the maiden all forlorn\n" + + "that milked the cow with the crumpled horn\n" + + "that tossed the dog\n" + + "that worried the cat\n" + + "that killed the rat\n" + + "that ate the malt\n" + + "that lay in the house that Jack built.\n\n" + + + "This is the farmer sowing his corn\n" + + "that kept the rooster that crowed in the morn\n" + + "that woke the priest all shaven and shorn\n" + + "that married the man all tattered and torn\n" + + "that kissed the maiden all forlorn\n" + + "that milked the cow with the crumpled horn\n" + + "that tossed the dog\n" + + "that worried the cat\n" + + "that killed the rat\n" + + "that ate the malt\n" + + "that lay in the house that Jack built.\n\n" + + + "This is the horse and the hound and the horn\n" + + "that belonged to the farmer sowing his corn\n" + + "that kept the rooster that crowed in the morn\n" + + "that woke the priest all shaven and shorn\n" + + "that married the man all tattered and torn\n" + + "that kissed the maiden all forlorn\n" + + "that milked the cow with the crumpled horn\n" + + "that tossed the dog\n" + + "that worried the cat\n" + + "that killed the rat\n" + + "that ate the malt\n" + + "that lay in the house that Jack built." + XCTAssertEqual(expected, House.recite()) } - - } diff --git a/exercises/kindergarten-garden/KindergartenGardenExample.swift b/exercises/kindergarten-garden/KindergartenGardenExample.swift index d9d25aec0..2541ab863 100644 --- a/exercises/kindergarten-garden/KindergartenGardenExample.swift +++ b/exercises/kindergarten-garden/KindergartenGardenExample.swift @@ -1,7 +1,5 @@ import Foundation - - enum Plant: String { case Grass = "G" case Clover = "C" @@ -11,54 +9,48 @@ enum Plant: String { struct Garden { static private let defaultChildren = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred", "Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"] - + private let pots: [String : [Plant]] - + init(_ diagram: String, children: [String] = defaultChildren) { self.pots = Garden.parse(diagram, children: children) } - - func plantsForChild(child: String) -> [Plant] { + + func plantsForChild(_ child: String) -> [Plant] { guard let plants = pots[child] else { return [] } return plants } - - private static func parse(diagram: String, children: [String]) -> [String : [Plant]] { - #if swift(>=3.0) - let sortedChildren = children.sorted(isOrderedBefore: <) - let lines = diagram.componentsSeparatedByCharacters(in: NSCharacterSet.newline()) - #else - let sortedChildren = children.sort(<) - let lines = diagram.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) - #endif - + + private static func parse(_ diagram: String, children: [String]) -> [String : [Plant]] { + let sortedChildren = children.sorted(isOrderedBefore: <) + let lines = diagram.components(separatedBy: CharacterSet.newlines) var result = [String : [Plant]]() var line1 = lines[0].characters.map { String($0) } var line2 = lines[1].characters.map { String($0) } - + var index = 0 - + for child in sortedChildren { guard index < line1.count else { break } - + var pots = [Plant]() - + if let plant1 = Plant(rawValue: line1[index]), plant2 = Plant(rawValue: line1[index + 1]), plant3 = Plant(rawValue: line2[index]), plant4 = Plant(rawValue: line2[index + 1]) { pots = [plant1, plant2, plant3, plant4] } - + result[child] = pots - + index += 2 } - + return result } -} \ No newline at end of file +} diff --git a/exercises/kindergarten-garden/KindergartenGardenTest.swift b/exercises/kindergarten-garden/KindergartenGardenTest.swift index 5e370f6bc..d9eec066c 100644 --- a/exercises/kindergarten-garden/KindergartenGardenTest.swift +++ b/exercises/kindergarten-garden/KindergartenGardenTest.swift @@ -1,104 +1,104 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class KindergartenGardenTest: XCTestCase { - + private let fullGarden = Garden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") private let disorderedGarden = Garden("VCRRGVRG\nRVGCCGCV", children: ["Samantha", "Patricia", "Xander", "Roger"]) private static let diagram = "VCRRGVRG\nRVGCCGCV" private let garden1 = Garden(diagram, children: ["Alice", "Bob", "Charlie", "Dan"]) private let garden2 = Garden(diagram, children: ["Bob", "Charlie", "Dan", "Erin"]) - + func testAlicesGarden() { let garden = Garden("RC\nGG") XCTAssertEqual([.Radishes, .Clover, .Grass, .Grass], garden.plantsForChild("Alice")) } - + func testDifferentGardenForAlice() { let garden = Garden("VC\nRC") XCTAssertEqual([.Violets, .Clover, .Radishes, .Clover], garden.plantsForChild("Alice")) } - + func testBobsGarden() { let garden = Garden("VVCG\nVVRC") XCTAssertEqual([.Clover, .Grass, .Radishes, .Clover], garden.plantsForChild("Bob")) } - + func testBobAndCharliesGardens() { let garden = Garden("VVCCGG\nVVCCGG") XCTAssertEqual([.Clover, .Clover, .Clover, .Clover], garden.plantsForChild("Bob")) XCTAssertEqual([.Grass, .Grass, .Grass, .Grass], garden.plantsForChild("Charlie")) } - + // MARK: - Test full garden - + func testAlice() { XCTAssertEqual([.Violets, .Radishes, .Violets, .Radishes], fullGarden.plantsForChild("Alice")) } - + func testBob() { XCTAssertEqual([.Clover, .Grass, .Clover, .Clover], fullGarden.plantsForChild("Bob")) } - + func testCharlie() { XCTAssertEqual([.Violets, .Violets, .Clover, .Grass], fullGarden.plantsForChild("Charlie")) } - + func testDavid() { XCTAssertEqual([.Radishes, .Violets, .Clover, .Radishes], fullGarden.plantsForChild("David")) } - + func testEve() { XCTAssertEqual([.Clover, .Grass, .Radishes, .Grass], fullGarden.plantsForChild("Eve")) } - + func testFred() { XCTAssertEqual([.Grass, .Clover, .Violets, .Clover], fullGarden.plantsForChild("Fred")) } - + func testGinny() { XCTAssertEqual([.Clover, .Grass, .Grass, .Clover], fullGarden.plantsForChild("Ginny")) } - + func testHarriet() { XCTAssertEqual([.Violets, .Radishes, .Radishes, .Violets], fullGarden.plantsForChild("Harriet")) } - + func testIleana() { XCTAssertEqual([.Grass, .Clover, .Violets, .Clover], fullGarden.plantsForChild("Ileana")) } - + func testJoseph() { XCTAssertEqual([.Violets, .Clover, .Violets, .Grass], fullGarden.plantsForChild("Joseph")) } - + func testKincaid() { XCTAssertEqual([.Grass, .Clover, .Clover, .Grass], fullGarden.plantsForChild("Kincaid")) } - + func testLarry() { XCTAssertEqual([.Grass, .Violets, .Clover, .Violets], fullGarden.plantsForChild("Larry")) } - + // MARK: - Test disordered garden - + func testPatricia() { XCTAssertEqual([.Violets, .Clover, .Radishes, .Violets], disorderedGarden.plantsForChild("Patricia")) } - + func testRoger() { XCTAssertEqual([.Radishes, .Radishes, .Grass, .Clover], disorderedGarden.plantsForChild("Roger")) } - + func testSamantha() { XCTAssertEqual([.Grass, .Violets, .Clover, .Grass], disorderedGarden.plantsForChild("Samantha")) } - + func testXander() { XCTAssertEqual([.Radishes, .Grass, .Clover, .Violets], disorderedGarden.plantsForChild("Xander")) } - + // MARK: - Test two gardens, different students func testBobAndCharliePerGarden() { diff --git a/exercises/largest-series-product/LargestSeriesProductExample.swift b/exercises/largest-series-product/LargestSeriesProductExample.swift index 6d263330f..ab9d793d1 100644 --- a/exercises/largest-series-product/LargestSeriesProductExample.swift +++ b/exercises/largest-series-product/LargestSeriesProductExample.swift @@ -1,51 +1,49 @@ -// Foundation not needed - struct NumberSeries { - - enum Error: ErrorType { - case InvalidCharacter - case SpanLongerThanStringLength - case NegativeSpan + + enum Error: ErrorProtocol { + case invalidCharacter + case spanLongerThanStringLength + case negativeSpan } - + let numbers: [Int] - + init(_ numberString: String) throws { self.numbers = try numberString.characters.map { guard let intValue = Int(String($0)) else { - throw Error.InvalidCharacter + throw Error.invalidCharacter } return intValue } } - - func largestProduct(numberOfDigits: Int) throws -> Int { + + func largestProduct(_ numberOfDigits: Int) throws -> Int { guard numberOfDigits >= 0 else { - throw Error.NegativeSpan + throw Error.negativeSpan } - + let endIndex = numbers.count - numberOfDigits guard endIndex >= 0 else { - throw Error.SpanLongerThanStringLength + throw Error.spanLongerThanStringLength } - + var result = 0 - + for startIndex in 0 ... endIndex { let selectedNumbers = numbers[startIndex ..< startIndex + numberOfDigits] - + var total = 1 - + for selectedNumber in selectedNumbers { total *= selectedNumber } - + if total > result { result = total } } - + return result } - + } diff --git a/exercises/largest-series-product/LargestSeriesProductTest.swift b/exercises/largest-series-product/LargestSeriesProductTest.swift index f16e08ffd..64788aa9d 100644 --- a/exercises/largest-series-product/LargestSeriesProductTest.swift +++ b/exercises/largest-series-product/LargestSeriesProductTest.swift @@ -1,123 +1,123 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class LargestSeriesProductTest: XCTestCase { - + func testCanFindTheLargestProductOf2WithNumbersInOrder() { XCTAssertEqual(72, try? NumberSeries("0123456789").largestProduct(2)) } - + func testCanFindTheLargestProductOf2() { XCTAssertEqual(48, try? NumberSeries("576802143").largestProduct(2)) } - + func testFindsTheLargestProductIfSpanEqualsLength() { XCTAssertEqual(18, try? NumberSeries("29").largestProduct(2)) } - + func testCanFindTheLargestProductOf3WithNumbersInOrder() { XCTAssertEqual(504, try? NumberSeries("0123456789").largestProduct(3)) } - + func testCanFindTheLargestProductOf3() { XCTAssertEqual(270, try? NumberSeries("1027839564").largestProduct(3)) } - + func testCanFindTheLargestProductOf5WithNumbersInOrder() { XCTAssertEqual(15120, try? NumberSeries("0123456789").largestProduct(5)) } - + func testCanGetTheLargestProductOfABigNumber() { XCTAssertEqual(23520, try? NumberSeries("73167176531330624919225119674426574742355349194934").largestProduct(6)) } - + func testCanGetTheLargestProductOfAnotherBigNumber() { XCTAssertEqual(28350, try? NumberSeries("52677741234314237566414902593461595376319419139427").largestProduct(6)) } - + func testCanGetTheLargestProductOfABigNumberProjectEuler() { XCTAssertEqual(23514624000, try? NumberSeries("7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450").largestProduct(13)) } - + func testReportsZeroIfTheOnlyDigitsAreZero() { XCTAssertEqual(0, try? NumberSeries("0000").largestProduct(2)) } - + func testReportsZeroIfAllSpansIncludeZero() { XCTAssertEqual(0, try? NumberSeries("99099").largestProduct(3)) } - + func testRejectsSpanLongerThanStringLength() { var throwsSpanLongerThanStringLengthError = false - + defer { XCTAssertTrue(throwsSpanLongerThanStringLengthError) } - + do { let _ = try NumberSeries("123").largestProduct(4) - } catch NumberSeries.Error.SpanLongerThanStringLength { + } catch NumberSeries.Error.spanLongerThanStringLength { throwsSpanLongerThanStringLengthError = true } catch { return } } - + func testReports1ForEmptyStringAndEmptyProduct0Span() { XCTAssertEqual(1, try? NumberSeries("").largestProduct(0)) } - + func testReports1ForNonemptyStringAndEmptyProduct0Span() { XCTAssertEqual(1, try? NumberSeries("123").largestProduct(0)) } - + func testRejectsEmptyStringAndNonzeroSpan() { var throwsSpanLongerThanStringLengthError = false - + defer { XCTAssertTrue(throwsSpanLongerThanStringLengthError) } - + do { let _ = try NumberSeries("").largestProduct(1) - } catch NumberSeries.Error.SpanLongerThanStringLength { + } catch NumberSeries.Error.spanLongerThanStringLength { throwsSpanLongerThanStringLengthError = true } catch { return } } - + func testRejectsInvalidCharacterInDigits() { var throwsInvalidCharacterError = false - + defer { XCTAssertTrue(throwsInvalidCharacterError) } - + do { let _ = try NumberSeries("1234a5").largestProduct(2) - } catch NumberSeries.Error.InvalidCharacter { + } catch NumberSeries.Error.invalidCharacter { throwsInvalidCharacterError = true } catch { return } } - + func testRejectsNegativeSpan() { var throwsNegativeSpanError = false - + defer { XCTAssertTrue(throwsNegativeSpanError) } - + do { let _ = try NumberSeries("12345").largestProduct(-1) - } catch NumberSeries.Error.NegativeSpan { + } catch NumberSeries.Error.negativeSpan { throwsNegativeSpanError = true } catch { return } } - + } diff --git a/exercises/leap/LeapExample.swift b/exercises/leap/LeapExample.swift index 41764fa65..04f0e9811 100644 --- a/exercises/leap/LeapExample.swift +++ b/exercises/leap/LeapExample.swift @@ -1,15 +1,11 @@ -// Foundation not needed - - - struct Year { var year = 1900 init(calendarYear: Int) { year = calendarYear } var isLeapYear: Bool { - get { - return (year%4 == 0 && year%100 != 0 ) || year%400 == 0 + get { + return (year%4 == 0 && year%100 != 0 ) || year%400 == 0 + } } - } -} \ No newline at end of file +} diff --git a/exercises/leap/LeapTest.swift b/exercises/leap/LeapTest.swift index b4a6bc03b..5644a1de3 100644 --- a/exercises/leap/LeapTest.swift +++ b/exercises/leap/LeapTest.swift @@ -1,27 +1,27 @@ -import XCTest +#if swift(>=3.0) + import XCTest +#endif +class LeapTest: XCTestCase { + func testVanillaLeapYear() { + let year = Year(calendarYear: 1996) + XCTAssertTrue(year.isLeapYear) + } -class LeapTest : XCTestCase { + func testAnyOldYear() { + let year = Year(calendarYear: 1997) + XCTAssertFalse(year.isLeapYear) + } - func testVanillaLeapYear() { - let year = Year(calendarYear: 1996) - XCTAssertTrue(year.isLeapYear) - } + func testCentury() { + let year = Year(calendarYear: 1900) + XCTAssertFalse(year.isLeapYear) + } - func testAnyOldYear() { - let year = Year(calendarYear: 1997) - XCTAssertFalse(year.isLeapYear) - } + func testExceptionalCentury() { + let year = Year(calendarYear: 2400) + XCTAssertTrue(year.isLeapYear) + } - func testCentury() { - let year = Year(calendarYear: 1900) - XCTAssertFalse(year.isLeapYear) - } - - func testExceptionalCentury() { - let year = Year(calendarYear: 2400) - XCTAssertTrue(year.isLeapYear) - } - -} \ No newline at end of file +} diff --git a/exercises/linked-list/LinkedListExample.swift b/exercises/linked-list/LinkedListExample.swift index 7c650a615..f27ad9b9c 100644 --- a/exercises/linked-list/LinkedListExample.swift +++ b/exercises/linked-list/LinkedListExample.swift @@ -1,37 +1,33 @@ -// Foundation not needed - - - class Node { var value: T? = nil var next: Node? = nil var prev: Node? = nil - + init() { } - + init(value: T) { self.value = value } - + } class Deque { var count: Int = 0 var head: Node var tail: Node - + init() { self.head = Node() self.tail = head - + } - + func isEmpty() -> Bool { return self.count == 0 } - - func push(value: T) { + + func push(_ value: T) { let node = Node(value: value) if self.isEmpty() { self.head = node @@ -43,8 +39,8 @@ class Deque { } self.count += 1 } - - func unshift(value: T) { + + func unshift(_ value: T) { let node = Node(value: value) if self.isEmpty() { self.head = node @@ -56,10 +52,7 @@ class Deque { } self.count += 1 } - - - - + func pop() -> T? { if self.isEmpty() { return nil @@ -74,8 +67,6 @@ class Deque { return temp.value } } - - func shift() -> T? { if self.isEmpty() { return nil @@ -91,4 +82,3 @@ class Deque { } } } - diff --git a/exercises/linked-list/LinkedListTest.swift b/exercises/linked-list/LinkedListTest.swift index d28f17020..7eefb7e95 100644 --- a/exercises/linked-list/LinkedListTest.swift +++ b/exercises/linked-list/LinkedListTest.swift @@ -1,12 +1,10 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif // Use Optionals and Generic Classes - class LinkedListTest: XCTestCase { - + func testPushPop() { let deque = Deque() deque.push(10) @@ -14,7 +12,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(20, deque.pop() ?? 0 ) XCTAssertEqual(10, deque.pop() ?? 0 ) } - + func testPushShift() { let deque = Deque() deque.push(10) @@ -22,7 +20,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(10, deque.shift() ?? 0 ) XCTAssertEqual(20, deque.shift() ?? 0 ) } - + func testUnshiftShift() { let deque = Deque() deque.unshift(10) @@ -30,7 +28,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(20, deque.shift() ?? 0 ) XCTAssertEqual(10, deque.shift() ?? 0 ) } - + func testUnshiftPop() { let deque = Deque() deque.unshift(10) @@ -38,7 +36,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(10, deque.pop() ?? 0 ) XCTAssertEqual(20, deque.pop() ?? 0 ) } - + func testExampleMethodLength() { let deque = Deque() deque.push(10) @@ -52,5 +50,5 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(50, deque.pop() ?? 0 ) XCTAssertEqual(30, deque.shift() ?? 0 ) } - + } diff --git a/exercises/luhn/LuhnExample.swift b/exercises/luhn/LuhnExample.swift index 936dcbea0..14ca5dfd3 100644 --- a/exercises/luhn/LuhnExample.swift +++ b/exercises/luhn/LuhnExample.swift @@ -1,44 +1,40 @@ import Darwin +struct Luhn { + var number: Int64 = 0 + var addends: [Int] { return addendsFunc(number)} + var checksum: Int {return addends.reduce(0, combine: +) } + var isValid: Bool { return checksum % 10 == 0} -struct Luhn { - - var number:Int64 = 0 - var addends:[Int] { return addendsFunc(number)} - var checksum:Int {return addends.reduce(0, combine: +) } - var isValid : Bool { return checksum % 10 == 0} - - init(_ num:Int64){ + init(_ num: Int64) { self.number = num } - - static func create (num:Int64)->Double{ - - func createCheckDigit(value:Int) -> Int{ + + static func create (_ num: Int64) -> Double { + + func createCheckDigit(_ value: Int) -> Int { let nearestTen = Int(ceil((Double(value) / 10.00)) * 10) return nearestTen - value } - + let zeroCheckDigitNumber = num * 10 let luhn = Luhn(zeroCheckDigitNumber) - + if luhn.isValid { return Double(zeroCheckDigitNumber)} - + return Double((zeroCheckDigitNumber) + createCheckDigit(luhn.checksum)) - + } - - func addendsFunc(num:Int64)->[Int]{ - - #if swift(>=3.0) - func oddIndexInt64Minus9( input:[Int])->[Int]{ + + func addendsFunc(_ num: Int64) -> [Int] { + func oddIndexInt64Minus9( _ input: [Int]) -> [Int] { var input = input input = Array(input.reversed()) - var tempArray:[Int] = [] - for (inx, each) in input.enumerated(){ - var tempEach:Int = each + var tempArray: [Int] = [] + for (inx, each) in input.enumerated() { + var tempEach: Int = each if (inx+1) % 2 == 0 { tempEach *= 2 if tempEach > 10 { @@ -51,38 +47,14 @@ struct Luhn { } return tempArray } - - #else - func oddIndexInt64Minus9( input:[Int])->[Int]{ - var input = input - input = Array(input.reverse()) - var tempArray:[Int] = [] - for (inx, each) in input.enumerate(){ - var tempEach:Int = each - if (inx+1) % 2 == 0 { - tempEach *= 2 - if tempEach > 10 { - tempEach -= 9 - } - tempArray.insert(tempEach, atIndex: 0) - } else { - tempArray.insert(tempEach, atIndex: 0) - } - } - return tempArray - } - #endif - - func char2Int(input:Character)-> Int{ + func char2Int(_ input: Character) -> Int { let tempInt = Int(String(input)) ?? -1 // -1 = error return tempInt } - + let tempString = "\(num)" - - return oddIndexInt64Minus9(Array(tempString.characters).map{char2Int($0)}) + + return oddIndexInt64Minus9(Array(tempString.characters).map {char2Int($0)}) } - - - + } diff --git a/exercises/luhn/LuhnTest.swift b/exercises/luhn/LuhnTest.swift index 5b9ebfd9a..efee65d45 100644 --- a/exercises/luhn/LuhnTest.swift +++ b/exercises/luhn/LuhnTest.swift @@ -1,52 +1,52 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class LuhnTest: XCTestCase { - + func testAddends() { let luhn = Luhn(12_121) XCTAssertEqual([1, 4, 1, 4, 1], luhn.addends) } - + func testTooLargeAddend() { let luhn = Luhn(8631) XCTAssertEqual([7, 6, 6, 1], luhn.addends) } - + func testChecksum() { let luhn = Luhn(4913) XCTAssertEqual(22, luhn.checksum) } - + func testChecksumAgain() { let luhn = Luhn(201_773) XCTAssertEqual(21, luhn.checksum) } - + func testInvalidNumber() { let luhn = Luhn(738) - XCTAssertEqual (false ,luhn.isValid) + XCTAssertEqual (false, luhn.isValid) } - + func testValidNumber() { let luhn = Luhn(8_739_567) XCTAssertEqual (true, luhn.isValid) } - + func testCreateValidNumber() { let number = Luhn.create(123) XCTAssertEqual(1230, number) } - + func testCreateOtherValidNumber() { let number = Luhn.create(873_956) XCTAssertEqual(8_739_567, number) } - + func testCreateYetAnotherValidNumber() { let number = Luhn.create(837_263_756) XCTAssertEqual(8_372_637_564, number) } - + } diff --git a/exercises/matrix/MatrixExample.swift b/exercises/matrix/MatrixExample.swift index fff695020..290b4e283 100644 --- a/exercises/matrix/MatrixExample.swift +++ b/exercises/matrix/MatrixExample.swift @@ -1,44 +1,28 @@ -// Foundation not needed - - - - - struct Matrix { - + let rows: [[Int]] let columns: [[Int]] - + init(_ stringRepresentation: String) { var rows = [[Int]]() var columns = [[Int]]() - - - #if swift(>=3.0) + let rowItems = stringRepresentation.characters.split(separator: "\n") for item in rowItems { let elements = item.split(separator: " ").flatMap { Int(String($0)) } rows.append(elements) } - #else - let rowItems = stringRepresentation.characters.split("\n") - for item in rowItems { - let elements = item.split(" ").flatMap { Int(String($0)) } - rows.append(elements) - } - #endif - for i in 0 ..< rows[0].count { var column = [Int]() for row in rows { column.append(row[i]) } - + columns.append(column) } - + self.rows = rows self.columns = columns } - -} \ No newline at end of file + +} diff --git a/exercises/matrix/MatrixTest.swift b/exercises/matrix/MatrixTest.swift index c82bc77f6..947203bf1 100644 --- a/exercises/matrix/MatrixTest.swift +++ b/exercises/matrix/MatrixTest.swift @@ -1,37 +1,37 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class MatrixTest: XCTestCase { - + func testExtractARow() { let matrix = Matrix("1 2\n10 20") XCTAssertEqual([1, 2], matrix.rows[0]) } - + func testExtractSameRowAgain() { let matrix = Matrix("9 7\n8 6") XCTAssertEqual([9, 7], matrix.rows[0]) } - + func testExtractOtherRow() { let matrix = Matrix("9 8 7\n19 18 17") XCTAssertEqual([19, 18, 17], matrix.rows[1]) } - + func testExtractOtherRowAgain() { let matrix = Matrix("1 4 9\n16 25 36") XCTAssertEqual([16, 25, 36], matrix.rows[1]) } - + func testExtractAColumn() { let matrix = Matrix("1 2 3\n4 5 6\n7 8 9\n 8 7 6") XCTAssertEqual([1, 4, 7, 8], matrix.columns[0]) } - + func testExtractAnotherColumn() { let matrix = Matrix("89 1903 3\n18 3 1\n9 4 800") XCTAssertEqual([1903, 3, 4], matrix.columns[1]) } - + } diff --git a/exercises/meetup/MeetupExample.swift b/exercises/meetup/MeetupExample.swift index fd4b3aee4..896d8d7ef 100644 --- a/exercises/meetup/MeetupExample.swift +++ b/exercises/meetup/MeetupExample.swift @@ -1,7 +1,5 @@ import Darwin - - func == (lhs: String, rhs: Date) -> Bool { return lhs == rhs.description } @@ -9,37 +7,36 @@ func == (lhs: String, rhs: Date) -> Bool { func == (lhs: Date, rhs: Date) -> Bool { return lhs.description == rhs.description } +struct Date { - -struct Date{ - enum DateFormatingOption { case yyyy_MM_dd case yyyy_MM_dd_T_HH_mm_ss } - - var descriptionStyle:DateFormatingOption = .yyyy_MM_dd - - private var tmDateBacking:tm = tm() - - var year:Int32 { return tmDateBacking.tm_year + 1900 } - var month:Int32 { return tmDateBacking.tm_mon + 1 } - var day:Int32 { return tmDateBacking.tm_mday } - var hour:Int32 { return tmDateBacking.tm_hour } - var mins:Int32 { return tmDateBacking.tm_min } - var secs:Int32 { return tmDateBacking.tm_sec } - var weekday:Int32 { return tmDateBacking.tm_wday + 1 } - - init(_ input:tm){ + + var descriptionStyle: DateFormatingOption = .yyyy_MM_dd + + private var tmDateBacking: tm = tm() + + var year: Int32 { return tmDateBacking.tm_year + 1900 } + var month: Int32 { return tmDateBacking.tm_mon + 1 } + var day: Int32 { return tmDateBacking.tm_mday } + var hour: Int32 { return tmDateBacking.tm_hour } + var mins: Int32 { return tmDateBacking.tm_min } + var secs: Int32 { return tmDateBacking.tm_sec } + var weekday: Int32 { return tmDateBacking.tm_wday + 1 } + + @discardableResult + init(_ input: tm) { self.tmDateBacking = input } - - init(){ + + init() { let temp = tm() - Date.init(temp).tmDateBacking + Date.init(temp) } - - init(year:Int32, month:Int32, day:Int32, hour:Int32 = 0, mins:Int32 = 0, secs:Int32 = 0){ + + init(year: Int32, month: Int32, day: Int32, hour: Int32 = 0, mins: Int32 = 0, secs: Int32 = 0) { var date = tm() date.tm_year = year - 1900 date.tm_mon = month - 1 @@ -47,119 +44,113 @@ struct Date{ date.tm_hour = hour date.tm_min = mins date.tm_sec = secs - + // Automaticly sets the week day var d1 = timegm(&date) - self.tmDateBacking = gmtime(&d1).memory + self.tmDateBacking = gmtime(&d1).pointee } - - mutating func dateByAddingSeconds(seconds:Int) -> Date { + + mutating func dateByAddingSeconds(_ seconds: Int) -> Date { var d1 = timegm(&tmDateBacking) + seconds - let d2 = gmtime(&d1).memory + let d2 = gmtime(&d1).pointee return Date.init(d2) } - + } extension Date:CustomStringConvertible { + private func addLeadingZero(_ input: Int32) -> String { - - private func addLeadingZero(input:Int32) -> String { - if (0...9).contains(input) { - return "0\(input)" } - else { return String(input) } + return "0\(input)" } else { return String(input) } } - - var description:String { - - let date = [year, month, day, hour, mins, secs].map{addLeadingZero($0)} - + + var description: String { + + let date = [year, month, day, hour, mins, secs].map {addLeadingZero($0)} + let dateOnly = date[0] + "-" + date[1] + "-" + date[2] let dateTime = dateOnly + "T" + date[3] + ":" + date[4] + ":" + date[5] - - switch descriptionStyle{ + + switch descriptionStyle { case .yyyy_MM_dd : return dateOnly case .yyyy_MM_dd_T_HH_mm_ss : return dateTime } } } -extension Date{ - - init?(from:String){ +extension Date { + + init?(from: String) { guard let date = Date.dateFromString(from) else { return nil } tmDateBacking = date.tmDateBacking if from.characters.count > 10 { self.descriptionStyle = .yyyy_MM_dd_T_HH_mm_ss } } - - static func dateFromString(input:String) -> Date? { + + static func dateFromString(_ input: String) -> Date? { var year = Int32() var month = Int32() var day = Int32() var hour = Int32() var minute = Int32() var second = Int32() - - let dateTime = input.characters.split("T").map{String($0)} - let date = dateTime[0].characters.split("-").map{String($0)} + + let dateTime = input.characters.split(separator: "T").map {String($0)} + let date = dateTime[0].characters.split(separator: "-").map {String($0)} if date.count == 3 { year = Int32(date[0]) ?? 0 month = Int32(date[1]) ?? 0 day = Int32(date[2]) ?? 0 } - + if dateTime.count == 2 { - let time = dateTime[1].characters.split(":").map{String($0)} - if time.count == 3 { + let time = dateTime[1].characters.split(separator: ":").map {String($0)} + if time.count == 3 { hour = Int32(time[0]) ?? 0 minute = Int32(time[1]) ?? 0 second = Int32(time[2]) ?? 0 - + } } if year + month + day >= 3 { return Date(year: year, month: month, day: day, hour: hour, mins: minute, secs: second) - + } else { return nil } } } - - -struct Meetup{ +struct Meetup { private var dateStart = Date() private var dateEnd = Date() + func newDate(_ input: String) -> Date { - - func newDate(input:String) -> Date{ - return Date(from: input) ?? Date() } - - func day(dayOfTheWeek:Int, which:String) -> Date{ - var dateMonthWeekDays = [[Int32(),Int32()]] + + func day(_ dayOfTheWeek: Int, which: String) -> Date { + var dateMonthWeekDays = [[Int32(), Int32()]] var dateWeekDays = [Int32()] - + let starDay = dateStart.weekday - var month = Array(dateStart.day ... dateEnd.day).map{(($0 + 5 + starDay) % 7) + 1 } - - for (index , eachDay) in month.enumerate(){ - dateMonthWeekDays.append([index + 1,eachDay]) + var month = Array(dateStart.day ... dateEnd.day) + month = month.map {(($0 + 5 + starDay) % 7) + 1 } + + for (index, eachDay) in month.enumerated() { + dateMonthWeekDays.append([index + 1, eachDay]) dateWeekDays.append(eachDay)} - - func which2date(dateInput:String)->Date{ - + + func which2date(_ dateInput: String) -> Date { + if which == "teenth" { let teenthRange = Array(dateMonthWeekDays[13...19]) let teenth = teenthRange.filter({$0[1] == Int32(dayOfTheWeek) })[0][0] return Date(from: "\(dateStart.year)-\(dateStart.month)-\(teenth)") ?? Date() - + } let count = dateMonthWeekDays.filter({$0[1] == Int32(dayOfTheWeek) }).count - var dayIndex:Int = 0 - switch dateInput{ + var dayIndex: Int = 0 + switch dateInput { case "1st": dayIndex = 0 case "2nd": dayIndex = 1 case "3rd": dayIndex = 2 @@ -168,21 +159,21 @@ struct Meetup{ case "last": dayIndex = (count - 1) default: dayIndex = -1 } - + let first2last = dateMonthWeekDays.filter({$0[1] == Int32(dayOfTheWeek) })[dayIndex][0] ?? 0 - + return Date(from:"\(dateStart.year)-\(dateStart.month)-\(first2last)") ?? Date() } - + return which2date(which) } - - init(year:Int, month:Int){ + + init(year: Int, month: Int) { let meetDate1 = Date(from: "\(year)-\(month)-\(1)") ?? Date() var meetDate2 = Date(from: "\(year)-\(month+1)-\(1)") ?? Date() meetDate2 = meetDate2.dateByAddingSeconds(-1*24*60*60) self.dateStart = meetDate1 self.dateEnd = meetDate2 - + } } diff --git a/exercises/meetup/MeetupTest.swift b/exercises/meetup/MeetupTest.swift index 301c10111..140d81b65 100644 --- a/exercises/meetup/MeetupTest.swift +++ b/exercises/meetup/MeetupTest.swift @@ -1,58 +1,54 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class MeetupTest: XCTestCase { - + let dayOfWeek = (Sunday:1, Monday:2, Tuesday:3, Wednesday:4, Thursday:5, Friday:6, Saturday:7) - - let whichOptions = (first:"1st", second:"2nd", third:"3rd", fourth:"4th", last:"last",teenth:"teenth") - - + + let whichOptions = (first:"1st", second:"2nd", third:"3rd", fourth:"4th", last:"last", teenth:"teenth") func testMonteenthOfMay2013() { let meetUp = Meetup(year: 2013, month: 5) - XCTAssertEqual("2013-05-13", meetUp.day(dayOfWeek.Monday, which: whichOptions.teenth).description) + XCTAssertEqual("2013-05-13", meetUp.day(dayOfWeek.Monday, which: whichOptions.teenth).description) } - + func testSaturteenthOfFebruary2013() { let meetUp = Meetup(year: 2013, month: 2) XCTAssertEqual ("2013-02-16", meetUp.day(dayOfWeek.Saturday, which: whichOptions.teenth).description) } - + func testFirstTuesdayOfMay2013() { let meetUp = Meetup(year: 2013, month: 5) XCTAssertEqual("2013-05-07", meetUp.day(dayOfWeek.Tuesday, which: whichOptions.first).description) } - + func testSecondMondayOfApril2013() { let meetUp = Meetup(year: 2013, month: 4) XCTAssertEqual("2013-04-08", meetUp.day(dayOfWeek.Monday, which: whichOptions.second).description) } - + func testThirdThursdayOfSeptember2013() { let meetUp = Meetup(year: 2013, month: 9) XCTAssertEqual("2013-09-19", meetUp.day(dayOfWeek.Thursday, which: whichOptions.third).description) } - + func testFourthSundayOfMarch2013() { let meetUp = Meetup(year: 2013, month: 3) XCTAssertEqual("2013-03-24", meetUp.day(dayOfWeek.Sunday, which: whichOptions.fourth).description) } - + func testLastThursdayOfOctober2013() { let meetUp = Meetup(year: 2013, month: 10) XCTAssertEqual("2013-10-31", meetUp.day(dayOfWeek.Thursday, which: whichOptions.last).description) } - + func testLastWednesdayOfFebruary2012() { let meetUp = Meetup(year: 2012, month: 2) XCTAssertEqual("2012-02-29", meetUp.day(dayOfWeek.Wednesday, which: whichOptions.last).description) } - + func testFirstFridayOfDecember2012() { let meetUp = Meetup(year: 2012, month: 12) XCTAssertEqual("2012-12-07", meetUp.day(dayOfWeek.Friday, which: whichOptions.first).description) } - - } diff --git a/exercises/minesweeper/MinesweeperExample.swift b/exercises/minesweeper/MinesweeperExample.swift index 651750b48..4423abfb4 100644 --- a/exercises/minesweeper/MinesweeperExample.swift +++ b/exercises/minesweeper/MinesweeperExample.swift @@ -1,55 +1,35 @@ import Foundation - - struct Board { - + private let validCharacters: [Character] = ["+", "-", "|", "*", " "] private let rows: [String] - - #if swift(>=3.0) + enum Error: ErrorProtocol { - case DifferentLength - case FaultyBorder - case InvalidCharacter + case differentLength + case faultyBorder + case invalidCharacter } - #else - enum Error: ErrorType { - case DifferentLength - case FaultyBorder - case InvalidCharacter - } - #endif - + init(_ rows: [String]) throws { self.rows = rows - + try validateInput() } - + func transform() -> [String] { var result = [String]() - #if swift(>=3.0) let rowsEnumarated = rows.enumerated() - #else - let rowsEnumarated = rows.enumerate() - #endif - - for (i, row) in rowsEnumarated { var newRow = "" - #if swift(>=3.0) let rowCharsEnumarated = row.characters.enumerated() - #else - let rowCharsEnumarated = row.characters.enumerate() - #endif - + for (j, character) in rowCharsEnumarated { if character != " " { newRow += String(character) } else { let mineCount = mineCountForRow(row, i: i, j: j) - + if mineCount > 0 { newRow += String(mineCount) } else { @@ -59,103 +39,83 @@ struct Board { } result.append(newRow) } - + return result } - - private func mineCountForRow(row: String, i: Int, j: Int) -> Int { + + private func mineCountForRow(_ row: String, i: Int, j: Int) -> Int { // Must be split up to avoid error: "Expression was too complex to be solved in reasonable time." var surroundings = [row[j - 1], row[j + 1], rows[i - 1][j - 1]] surroundings += [rows[i - 1][j], rows[i - 1][j + 1]] - surroundings += [rows[i + 1][j - 1], rows[i + 1][j], rows[i + 1][j + 1]] - + surroundings += [rows[i + 1][j - 1]] + surroundings += [rows[i + 1][j], rows[i + 1][j + 1]] + return surroundings.filter { isMine($0) }.count } - - private func isMine(character: Character) -> Bool { + + private func isMine(_ character: Character) -> Bool { return character == "*" } - + private func validateInput() throws { try validateSize() try validateData() try validateBorders() } - + private func validateSize() throws { guard let count = rows.first?.characters.count else { - throw Error.DifferentLength + throw Error.differentLength } - + try rows.forEach { guard $0.characters.count == count else { - throw Error.DifferentLength + throw Error.differentLength } } } - + private func validateData() throws { try rows.forEach { try $0.characters.forEach { guard validCharacters.contains($0) else { - throw Error.InvalidCharacter + throw Error.invalidCharacter } } } } - + private func validateBorders() throws { let firstAndLast = [rows[0], rows[rows.count - 1]] try firstAndLast.forEach { guard $0.matchesRegex("^\\+[-]+\\+$") else { - throw Error.FaultyBorder + throw Error.faultyBorder } } - + let middleRows = rows[1 ..< rows.count - 2] try middleRows.forEach { guard $0.matchesRegex("^\\|.+\\|$") else { - throw Error.FaultyBorder + throw Error.faultyBorder } } } } -#if swift(>=3.0) private extension String { - func matchesRegex(pattern: String) -> Bool { - let options = NSRegularExpressionOptions.dotMatchesLineSeparators - let regex = try? NSRegularExpression(pattern: pattern, options: options) + func matchesRegex(_ pattern: String) -> Bool { + let options = RegularExpression.Options.dotMatchesLineSeparators + let regex = try? RegularExpression(pattern: pattern, options: options) var matches = 0 if let regex = regex { matches = regex.numberOfMatches(in: self, - options: [], - range: NSMakeRange(0, (self as NSString).length)) + options: [], + range: NSMakeRange(0, (self as NSString).length)) } return matches > 0 } subscript(index: Int) -> Character { - let index = startIndex.advanced(by:index) + let index = characters.index(startIndex, offsetBy: index) return self[index] } } - -#else - private extension String { - func matchesRegex(pattern: String) -> Bool { - let options = NSRegularExpressionOptions.DotMatchesLineSeparators - let regex = try? NSRegularExpression(pattern: pattern, options: options) - var matches = 0 - if let regex = regex { - matches = regex.numberOfMatchesInString(self, - options: [], - range: NSMakeRange(0, (self as NSString).length)) - } - return matches > 0 - } - subscript(index: Int) -> Character { - let index = startIndex.advancedBy(index) - return self[index] - } - } -#endif \ No newline at end of file diff --git a/exercises/minesweeper/MinesweeperTest.swift b/exercises/minesweeper/MinesweeperTest.swift index b7e6d8457..14859caa5 100644 --- a/exercises/minesweeper/MinesweeperTest.swift +++ b/exercises/minesweeper/MinesweeperTest.swift @@ -1,118 +1,118 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class MinesweeperTest: XCTestCase { - + func testTransform1() { let input = ["+------+", "| * * |", "| * |", "| * |", "| * *|", - "| * * |", "| |", "+------+"] + "| * * |", "| |", "+------+"] let output = ["+------+", "|1*22*1|", "|12*322|", "| 123*2|", "|112*4*|", - "|1*22*2|", "|111111|", "+------+"] + "|1*22*2|", "|111111|", "+------+"] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform2() { let input = ["+-----+", "| * * |", "| |", "| * |", "| * *|", - "| * * |", "+-----+"] + "| * * |", "+-----+"] let output = ["+-----+", "|1*2*1|", "|11322|", "| 12*2|", "|12*4*|", - "|1*3*2|", "+-----+"] + "|1*3*2|", "+-----+"] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform3() { let input = ["+-----+", "| * * |", "+-----+"] let output = ["+-----+", "|1*2*1|", "+-----+"] XCTAssertEqual(output, try! Board(input).transform()) } - + func test_transform4() { let input = ["+-+", "|*|", "| |", "|*|", "| |", "| |", "+-+"] let output = ["+-+", "|*|", "|2|", "|*|", "|1|", "| |", "+-+"] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform5() { let input = ["+-+", "|*|", "+-+"] let output = ["+-+", "|*|", "+-+"] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform6() { let input = ["+--+", "|**|", "|**|", "+--+"] let output = ["+--+", "|**|", "|**|", "+--+"] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform7() { let input = ["+--+", "|**|", "|**|", "+--+"] let output = ["+--+", "|**|", "|**|", "+--+"] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform8() { let input = ["+---+", "|***|", "|* *|", "|***|", "+---+"] let output = ["+---+", "|***|", "|*8*|", "|***|", "+---+"] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform9() { let input = ["+-----+", "| |", "| * |", "| |", "| |", - "| * |", "+-----+"] + "| * |", "+-----+"] let output = ["+-----+", "| 111|", "| 1*1|", "| 111|", "|111 |", - "|1*1 |", "+-----+"] + "|1*1 |", "+-----+"] XCTAssertEqual(output, try! Board(input).transform()) } - + func testDifferentLength() { var throwsDifferentLengthError = false - + defer { XCTAssertTrue(throwsDifferentLengthError) } - + let input = ["+-+", "| |", "|* |", "| |", "+-+"] do { let _ = try Board(input) - } catch Board.Error.DifferentLength { + } catch Board.Error.differentLength { throwsDifferentLengthError = true } catch { return } } - + func testFaultyBorder() { var throwsFaultyBorderError = false - + defer { XCTAssertTrue(throwsFaultyBorderError) } - + let input = ["+-----+", "* * |", "+-- --+"] do { let _ = try Board(input) - } catch Board.Error.FaultyBorder { + } catch Board.Error.faultyBorder { throwsFaultyBorderError = true } catch { return } } - + func testInvalidCharacter() { var throwsInvalidCharacterError = false - + defer { XCTAssertTrue(throwsInvalidCharacterError) } - + let input = ["+-----+", "|X * |", "+-----+"] do { let _ = try Board(input) - } catch Board.Error.InvalidCharacter { + } catch Board.Error.invalidCharacter { throwsInvalidCharacterError = true } catch { return } } - + } diff --git a/exercises/nth-prime/NthPrimeExample.swift b/exercises/nth-prime/NthPrimeExample.swift index 02a86a8ac..11e4dfac5 100644 --- a/exercises/nth-prime/NthPrimeExample.swift +++ b/exercises/nth-prime/NthPrimeExample.swift @@ -1,39 +1,37 @@ import Darwin - - struct Prime { - static func nth(nth: Int) -> Int? { + static func nth(_ nth: Int) -> Int? { if nth < 1 { return nil } - + var primes = 0 var i = 1 - + while primes < nth { i += 1 if isPrime(i) { primes += 1 } } - + return i } - - private static func isPrime(number: Int) -> Bool { + + private static func isPrime(_ number: Int) -> Bool { if number == 1 { return false } else if number == 2 { return true } - + for i in 2...Int(ceil(sqrt(Double(number)))) { if number % i == 0 { return false } } - + return true } } diff --git a/exercises/nth-prime/NthPrimeTest.swift b/exercises/nth-prime/NthPrimeTest.swift index 847608b32..2bd364e40 100644 --- a/exercises/nth-prime/NthPrimeTest.swift +++ b/exercises/nth-prime/NthPrimeTest.swift @@ -1,27 +1,27 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class NthPrimeTest: XCTestCase { - + func testFirst() { XCTAssertEqual(2, Prime.nth(1)) } - + func testSecond() { XCTAssertEqual(3, Prime.nth(2)) } - + func testSixthPrime() { XCTAssertEqual(13, Prime.nth(6)) } - + func testBigPrime() { XCTAssertEqual(104_743, Prime.nth(10_001)) } - + func testWeirdCase() { XCTAssertNil(Prime.nth(0)) } - + } diff --git a/exercises/nucleotide-count/NucleotideCountExample.swift b/exercises/nucleotide-count/NucleotideCountExample.swift index 06b3c9740..4b46151ff 100644 --- a/exercises/nucleotide-count/NucleotideCountExample.swift +++ b/exercises/nucleotide-count/NucleotideCountExample.swift @@ -1,45 +1,36 @@ -// Foundation not needed - - - enum Nucleobase: Character { - case Adenine = "A", - Cytosine = "C", - Thymine = "T", - Guanine = "G" + case adenine = "A", + cytosine = "C", + thymine = "T", + guanine = "G" } struct DNA { - - var nucleotideCounts:[Nucleobase:Int] = [ .Adenine: 0, .Thymine: 0, .Cytosine: 0 , .Guanine : 0 ] - + + var nucleotideCounts: [Nucleobase:Int] = [ .adenine: 0, .thymine: 0, .cytosine: 0, .guanine : 0 ] + init?(strand: String) { - #if swift(>=3.0) let enumarated = strand.characters.enumerated() - #else - let enumarated = strand.characters.enumerate() - #endif + for (_, value) in enumarated { if let possibleNucleobase = Nucleobase(rawValue: value) { nucleotideCounts[possibleNucleobase]! += 1 - } - else { + } else { return nil } } } - - func count(value :Character)-> Int { + + func count(_ value: Character) -> Int { return nucleotideCounts[Nucleobase(rawValue: value)!]! } - - func counts()->[String: Int] { - var nCounts:[String:Int] = [:] + + func counts() -> [String: Int] { + var nCounts: [String:Int] = [:] for (k, v) in nucleotideCounts { nCounts[String(k.rawValue)] = v } return nCounts } - -} +} diff --git a/exercises/nucleotide-count/NucleotideCountTest.swift b/exercises/nucleotide-count/NucleotideCountTest.swift index 013236948..8f0d8c546 100644 --- a/exercises/nucleotide-count/NucleotideCountTest.swift +++ b/exercises/nucleotide-count/NucleotideCountTest.swift @@ -1,60 +1,59 @@ -import XCTest +#if swift(>=3.0) + import XCTest +#endif - - -class NucleotideCountTest: XCTestCase -{ +class NucleotideCountTest: XCTestCase { func testEmptyDNAStringHasNoAdenosine() { let dna = DNA(strand: "")! let result = dna.count("A") let expected = 0 XCTAssertEqual(result, expected) } - + func testEmptyDNAStringHasNoNucleotides() { let dna = DNA(strand: "")! let results = dna.counts() let expected = ["T": 0, "A": 0, "C": 0, "G": 0] XCTAssertEqual(results, expected) } - + func testRepetitiveCytidineGetsCounted() { let dna = DNA(strand: "CCCCC")! let result = dna.count("C") let expected = 5 XCTAssertEqual(result, expected) } - + func testRepetitiveSequenceHasOnlyGuanosine() { let dna = DNA(strand: "GGGGGGGG")! let results = dna.counts() - let expected = [ "A": 0, "T": 0, "C": 0 , "G": 8 ] + let expected = [ "A": 0, "T": 0, "C": 0, "G": 8 ] XCTAssertEqual(results, expected) } - + func testCountsByThymidine() { let dna = DNA(strand: "GGGGGTAACCCGG")! let result = dna.count("T") let expected = 1 XCTAssertEqual(result, expected) } - + func testCountsANucleotideOnlyOnce() { let dna = DNA(strand: "CGATTGGG")! let result = dna.count("T") let expected = 2 XCTAssertEqual(result, expected) } - + func testValidatesDNA() { XCTAssert(DNA(strand: "John") == nil ) } - + func testCountsAllNucleotides() { let longStrand = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC" let dna = DNA(strand: longStrand)! let results = dna.counts() - let expected = [ "A": 20, "T": 21,"C": 12 , "G" : 17 ] + let expected = [ "A": 20, "T": 21, "C": 12, "G" : 17 ] XCTAssertEqual(results, expected) } -} \ No newline at end of file +} diff --git a/exercises/ocr-numbers/OcrNumbersExample.swift b/exercises/ocr-numbers/OcrNumbersExample.swift index ccb8daf1e..396b3dcdc 100644 --- a/exercises/ocr-numbers/OcrNumbersExample.swift +++ b/exercises/ocr-numbers/OcrNumbersExample.swift @@ -1,112 +1,84 @@ -// Foundation not needed - - - struct OCR { - + let lines: [String] let patterns = [ - [" _ ", "| |", "|_|", " "] : "0", - [" ", " |", " |", " "] : "1", - [" _ ", " _|", "|_ ", " "] : "2", - [" _ ", " _|", " _|", " "] : "3", - [" ", "|_|", " |", " "] : "4", - [" _ ", "|_ ", " _|", " "] : "5", - [" _ ", "|_ ", "|_|", " "] : "6", - [" _ ", " |", " |", " "] : "7", - [" _ ", "|_|", "|_|", " "] : "8", - [" _ ", "|_|", " _|", " "] : "9" + [" _ ", "| |", "|_|", " "] : "0", + [" ", " |", " |", " "] : "1", + [" _ ", " _|", "|_ ", " "] : "2", + [" _ ", " _|", " _|", " "] : "3", + [" ", "|_|", " |", " "] : "4", + [" _ ", "|_ ", " _|", " "] : "5", + [" _ ", "|_ ", "|_|", " "] : "6", + [" _ ", " |", " |", " "] : "7", + [" _ ", "|_|", "|_|", " "] : "8", + [" _ ", "|_|", " _|", " "] : "9" ] - - #if swift(>=3.0) + enum Error: ErrorProtocol { - case InvalidNumberOfLines - case InvalidNumberOfColumns - } - #else - enum Error: ErrorType { - case InvalidNumberOfLines - case InvalidNumberOfColumns + case invalidNumberOfLines + case invalidNumberOfColumns } - #endif - init(_ text: String) throws { - #if swift(>=3.0) - let lines = text.characters.split(separator: "\n").map { String($0) } - #else - let lines = text.characters.split("\n").map { String($0) } - - #endif - + let lines = text.characters.split(separator: "\n").map { String($0) } + let rowCount = lines.count - + guard rowCount > 0 && rowCount % 4 == 0 else { - throw Error.InvalidNumberOfLines + throw Error.invalidNumberOfLines } - + let columnCount = lines[0].characters.count - + guard columnCount > 0 && columnCount % 3 == 0 else { - throw Error.InvalidNumberOfColumns + throw Error.invalidNumberOfColumns } - + try lines.forEach { guard $0.characters.count == columnCount else { - throw Error.InvalidNumberOfColumns + throw Error.invalidNumberOfColumns } } - + self.lines = lines } - + func converted() -> String { var resultArray = [String]() - + var rowIndex = 0 - + while rowIndex < lines.count { let selectedLines = lines[rowIndex ... rowIndex + 3] var result = "" - + var columnIndex = 0 - + while columnIndex < lines[0].characters.count { var grouping = [String]() - + for line in selectedLines { - #if swift(>=3.0) - let startIndex = line.startIndex.advanced(by:columnIndex) - let endIndex = line.startIndex.advanced(by:columnIndex + 2) - grouping.append(line[startIndex...endIndex]) - #else - let startIndex = line.startIndex.advancedBy(columnIndex) - let endIndex = line.startIndex.advancedBy(columnIndex + 2) - grouping.append(line[startIndex...endIndex]) - - #endif - + let startIndex = line.characters.index(line.startIndex, offsetBy: columnIndex) + let endIndex = line.characters.index(line.startIndex, offsetBy: columnIndex + 2) + grouping.append(line[startIndex...endIndex]) + } - + result += patternForGrouping(grouping) columnIndex += 3 } - + resultArray.append(result) rowIndex += 4 } - #if swift(>=3.0) return resultArray.joined(separator: ",") - #else - return resultArray.joinWithSeparator(",") - #endif + } - - func patternForGrouping(grouping: [String]) -> String { + + func patternForGrouping(_ grouping: [String]) -> String { guard let number = patterns[grouping] else { return "?" } return number } - -} +} diff --git a/exercises/ocr-numbers/OcrNumbersTest.swift b/exercises/ocr-numbers/OcrNumbersTest.swift index eaddfa7d0..e5c6d2e2c 100644 --- a/exercises/ocr-numbers/OcrNumbersTest.swift +++ b/exercises/ocr-numbers/OcrNumbersTest.swift @@ -1,189 +1,189 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class OcrNumbersTest: XCTestCase { - + func testRecognizeZero() { let text = " _ \n" + - "| |\n" + - "|_|\n" + - " " + "| |\n" + + "|_|\n" + + " " XCTAssertEqual("0", try? OCR(text).converted()) } - + func testRecognizeOne() { let text = " \n" + - " |\n" + - " |\n" + - " " + " |\n" + + " |\n" + + " " XCTAssertEqual("1", try? OCR(text).converted()) } func testRecognizeTwo() { let text = " _ \n" + - " _|\n" + - "|_ \n" + - " " + " _|\n" + + "|_ \n" + + " " XCTAssertEqual("2", try? OCR(text).converted()) } - + func testRecognizeThree() { let text = " _ \n" + - " _|\n" + - " _|\n" + - " " + " _|\n" + + " _|\n" + + " " XCTAssertEqual("3", try? OCR(text).converted()) } - + func testRecognizeFour() { let text = " \n" + - "|_|\n" + - " |\n" + - " " + "|_|\n" + + " |\n" + + " " XCTAssertEqual("4", try? OCR(text).converted()) } - + func testRecognizeFive() { let text = " _ \n" + - "|_ \n" + - " _|\n" + - " " + "|_ \n" + + " _|\n" + + " " XCTAssertEqual("5", try? OCR(text).converted()) } - + func testRecognizeSix() { let text = " _ \n" + - "|_ \n" + - "|_|\n" + - " " + "|_ \n" + + "|_|\n" + + " " XCTAssertEqual("6", try? OCR(text).converted()) } func testRecognizeSeven() { let text = " _ \n" + - " |\n" + - " |\n" + - " " + " |\n" + + " |\n" + + " " XCTAssertEqual("7", try? OCR(text).converted()) } - + func testRecognizeEight() { let text = " _ \n" + - "|_|\n" + - "|_|\n" + - " " + "|_|\n" + + "|_|\n" + + " " XCTAssertEqual("8", try? OCR(text).converted()) } func testRecognizeNine() { let text = " _ \n" + - "|_|\n" + - " _|\n" + - " " + "|_|\n" + + " _|\n" + + " " XCTAssertEqual("9", try? OCR(text).converted()) } - + func testIdentifyGarble() { let text = " \n" + - "| |\n" + - "| |\n" + - " " + "| |\n" + + "| |\n" + + " " XCTAssertEqual("?", try? OCR(text).converted()) } - + func testIdentify10() { let text = " _ \n" + - " || |\n" + - " ||_|\n" + - " " + " || |\n" + + " ||_|\n" + + " " XCTAssertEqual("10", try? OCR(text).converted()) } - + func testIdentify110101100() { let text = " _ _ _ _ \n" + - " | || | || | | || || |\n" + - " | ||_| ||_| | ||_||_|\n" + - " " + " | || | || | | || || |\n" + + " | ||_| ||_| | ||_||_|\n" + + " " XCTAssertEqual("110101100", try? OCR(text).converted()) } - + func testIdentifyWithGarble() { let text = " _ _ _ \n" + - " | || | || | || || |\n" + - " | | _| ||_| | ||_||_|\n" + - " " + " | || | || | || || |\n" + + " | | _| ||_| | ||_||_|\n" + + " " XCTAssertEqual("11?10?1?0", try? OCR(text).converted()) } - + func testIdentify1234567890() { let text = " _ _ _ _ _ _ _ _ \n" + - " | _| _||_||_ |_ ||_||_|| |\n" + - " ||_ _| | _||_| ||_| _||_|\n" + - " " + " | _| _||_||_ |_ ||_||_|| |\n" + + " ||_ _| | _||_| ||_| _||_|\n" + + " " XCTAssertEqual("1234567890", try? OCR(text).converted()) } - + func testIdentify123_456_789() { let text = " _ _ \n" + - " | _| _|\n" + - " ||_ _|\n" + - " \n" + - " _ _ \n" + - "|_||_ |_ \n" + - " | _||_|\n" + - " \n" + - " _ _ _ \n" + - " ||_||_|\n" + - " ||_| _|\n" + - " " + " | _| _|\n" + + " ||_ _|\n" + + " \n" + + " _ _ \n" + + "|_||_ |_ \n" + + " | _||_|\n" + + " \n" + + " _ _ _ \n" + + " ||_||_|\n" + + " ||_| _|\n" + + " " XCTAssertEqual("123,456,789", try? OCR(text).converted()) } - + func testThrowsInvalidNumberOfLinesError() { var throwsInvalidNumberOfLinesError = false - + defer { XCTAssertTrue(throwsInvalidNumberOfLinesError) } - + do { let text = " _ _ \n" + - " | _| _|" + " | _| _|" let _ = try OCR(text) - } catch OCR.Error.InvalidNumberOfLines { + } catch OCR.Error.invalidNumberOfLines { throwsInvalidNumberOfLinesError = true return } catch { return } } - + func testThrowsInvalidNumberOfColumnsError() { var throwsInvalidNumberOfColumnsError = false - + defer { XCTAssertTrue(throwsInvalidNumberOfColumnsError) } - + do { let text = " _\n" + - " | _\n" + - " ||_\n" + - " " + " | _\n" + + " ||_\n" + + " " let _ = try OCR(text) - } catch OCR.Error.InvalidNumberOfColumns { + } catch OCR.Error.invalidNumberOfColumns { throwsInvalidNumberOfColumnsError = true return } catch { return } } - + } diff --git a/exercises/octal/OctalExample.swift b/exercises/octal/OctalExample.swift index 89945d623..543e92b98 100644 --- a/exercises/octal/OctalExample.swift +++ b/exercises/octal/OctalExample.swift @@ -1,42 +1,38 @@ import Darwin +extension Int { - -extension Int{ - - init(_ value:Octal){ + init(_ value: Octal) { self = value.toDecimal } - + } struct Octal { private var stringValue = "" - private var toDecimal:Int = 0 - private func isValidOctal() -> Bool{ + private var toDecimal: Int = 0 + private func isValidOctal() -> Bool { return (Int(stringValue) ?? -1) > -1 ? true : false } - - private func oct2int(input:String)->Int{ - let orderedInput = Array(input.characters.reverse()) - var tempInt:Int = 0 - for (inx,each) in orderedInput.enumerate(){ + + private func oct2int(_ input: String) -> Int { + let orderedInput = Array(input.characters.reversed()) + var tempInt: Int = 0 + for (inx, each) in orderedInput.enumerated() { let tempCharInt = Int("\(each)") ?? 0 if tempCharInt > 7 {return 0} - let tempOctPower = Int(pow(Double(8),Double(inx))) + let tempOctPower = Int(pow(Double(8), Double(inx))) tempInt += tempOctPower * tempCharInt } return tempInt } - - - init( _ sv:String){ + init( _ sv: String) { self.stringValue = sv - + if isValidOctal() { self.toDecimal = oct2int(sv) } - + } - -} \ No newline at end of file + +} diff --git a/exercises/octal/OctalTest.swift b/exercises/octal/OctalTest.swift index e97e4d103..bff232761 100644 --- a/exercises/octal/OctalTest.swift +++ b/exercises/octal/OctalTest.swift @@ -1,65 +1,62 @@ -import XCTest +#if swift(>=3.0) + import XCTest +#endif +class OctalTest: XCTestCase { - -class OctalTest: XCTestCase -{ - func testOctal1IsDecimal1() { XCTAssertEqual(1, Int(Octal("1"))) } - + func testOctal10IsDecimal8() { XCTAssertEqual(8, Int(Octal("10"))) } - + func testOctal17IsDecimal15() { XCTAssertEqual(15, Int(Octal("17"))) } - + func testOctal11IsDecimal9() { XCTAssertEqual(9, Int(Octal("11"))) } - + func testOctal130IsDecimal88() { XCTAssertEqual(88, Int(Octal("130"))) } - + func testOctal2047IsDecimal1063() { XCTAssertEqual(1063, Int(Octal("2047"))) } - + func testOctal7777IsDecimal4095() { XCTAssertEqual(4095, Int(Octal("7777"))) } - + func testOctal1234567IsDecimal342391() { XCTAssertEqual(342391, Int(Octal("1234567"))) } - + func testInvalidOctalIsDecimal0() { XCTAssertEqual(0, Int(Octal("carrot"))) } - + func test8IsseenasInvalidandreturns0() { XCTAssertEqual(0, Int(Octal("8"))) } - + func test9IsseenasInvalidandreturns0() { XCTAssertEqual(0, Int(Octal("9"))) } - + func test6789IsseenasInvalidandreturns0() { XCTAssertEqual(0, Int(Octal("6789"))) } - + func testabc1zIsseenasInvalidandreturns0() { XCTAssertEqual(0, Int(Octal("abc1z"))) } - + func testvalidOctalformattedstring011IsDecimal9() { XCTAssertEqual(9, Int(Octal("011"))) } - - -} \ No newline at end of file +} diff --git a/exercises/palindrome-products/PalindromeProductsExample.swift b/exercises/palindrome-products/PalindromeProductsExample.swift index ac38ef345..da372c020 100644 --- a/exercises/palindrome-products/PalindromeProductsExample.swift +++ b/exercises/palindrome-products/PalindromeProductsExample.swift @@ -1,12 +1,11 @@ import Foundation -// Apple Swift version 2.1 private extension String { - + var length: Int {return self.characters.count} - + func reverse() -> String { - var result:String = "" + var result: String = "" for char in self.characters { result = "\(char)\(result)" } @@ -14,58 +13,56 @@ private extension String { } } -struct PalindromeProducts{ - - typealias Palindrome = (value:Int, factor:[Int]) - private let maxFactor:Int - private let minFactor:Int - - var largest:Palindrome {return calculate(.max)} - var smallest:Palindrome {return calculate(.min)} - +struct PalindromeProducts { + + typealias Palindrome = (value: Int, factor: [Int]) + private let maxFactor: Int + private let minFactor: Int + + var largest: Palindrome {return calculate(.max)} + var smallest: Palindrome {return calculate(.min)} + init(maxFactor: Int, minFactor: Int = 1) { self.maxFactor = maxFactor self.minFactor = minFactor } - + private enum Mode { case max, min } - private func calculate(upTo:Mode)->Palindrome{ - + private func calculate(_ upTo: Mode) -> Palindrome { + let rangeOuter = minFactor...maxFactor var multiplications = [Palindrome]() - + //Multitreaded code - let queue = dispatch_queue_create("io.exercism.multiQueuePali", DISPATCH_QUEUE_CONCURRENT) - var results = [[Palindrome]](count: rangeOuter.count, repeatedValue: [Palindrome]()) - - dispatch_apply(rangeOuter.count, queue){ + var results = [[Palindrome]](repeating: [Palindrome](), count: rangeOuter.count) + + DispatchQueue.concurrentPerform(iterations: rangeOuter.count) { advanceByIndex in var multiplicationsTemp = [Palindrome]() - let each = rangeOuter.startIndex.advancedBy(advanceByIndex) - let innerRangeCustom = each.. $1.0}) - - if let large = multiplications.first, let small = multiplications.last{ - switch upTo{ + multiplications = results.flatten().sorted(isOrderedBefore: {$0.0 > $1.0}) + + if let large = multiplications.first, let small = multiplications.last { + switch upTo { case .max : return large case .min : return small } } else { - switch upTo{ - case .max : return (self.maxFactor,[self.maxFactor, 1]) - case .min : return (self.minFactor,[self.minFactor, 1]) + switch upTo { + case .max : return (self.maxFactor, [self.maxFactor, 1]) + case .min : return (self.minFactor, [self.minFactor, 1]) } } } } - - diff --git a/exercises/palindrome-products/PalindromeProductsTest.swift b/exercises/palindrome-products/PalindromeProductsTest.swift index ec860d14c..bd121a141 100644 --- a/exercises/palindrome-products/PalindromeProductsTest.swift +++ b/exercises/palindrome-products/PalindromeProductsTest.swift @@ -1,16 +1,16 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class PalindromeProductsTest: XCTestCase { - + func testLargestPalindromeFromSingleDigitFactors() { let palindromes = PalindromeProducts(maxFactor: 9) let largest = palindromes.largest XCTAssertEqual(9, largest.value) XCTAssertTrue(Set([1, 9]) == Set(largest.factor) || Set([3, 3]) == Set(largest.factor) ) } - + func testLargestPalindromeFromDoubleDigitFactors() { let palindromes = PalindromeProducts(maxFactor: 99, minFactor: 10) let largest = palindromes.largest @@ -24,19 +24,19 @@ class PalindromeProductsTest: XCTestCase { XCTAssertEqual(121, smallest.value) XCTAssertEqual(Set([11, 11]), Set(smallest.factor)) } - + func testLargestPalindromeFromTripleDigitFactors() { let palindromes = PalindromeProducts(maxFactor: 999, minFactor: 100) let largest = palindromes.largest XCTAssertEqual(906_609, largest.value) XCTAssertEqual(Set([913, 993]), Set(largest.factor)) } - + func testSmallestPalindromeFromTripleDigitFactors() { let palindromes = PalindromeProducts(maxFactor: 999, minFactor: 100) let smallest = palindromes.smallest XCTAssertEqual(10_201, smallest.value) XCTAssertEqual(Set([101, 101]), Set(smallest.factor)) } - + } diff --git a/exercises/pascals-triangle/PascalsTriangleExample.swift b/exercises/pascals-triangle/PascalsTriangleExample.swift index aa8b8dc83..476338dd6 100644 --- a/exercises/pascals-triangle/PascalsTriangleExample.swift +++ b/exercises/pascals-triangle/PascalsTriangleExample.swift @@ -1,14 +1,10 @@ -// Foundation not needed - - - struct PascalsTriangle { - + let rows: [[Int]] - + init(_ numberOfRows: Int) { var triangle = [[Int]]() - + for rowNumber in 0..=3.0) + import XCTest +#endif class PascalsTriangleTest: XCTestCase { - + func testOneRow() { let triangle = PascalsTriangle(1) XCTAssertEqual([[1]], triangle.rows) } - + func testTwoRows() { let triangle = PascalsTriangle(2) XCTAssertEqual([[1], [1, 1]], triangle.rows) } - + func testThreeRows() { let triangle = PascalsTriangle(3) XCTAssertEqual([[1], [1, 1], [1, 2, 1]], triangle.rows) } - + func testFourthRow() { let triangle = PascalsTriangle(4) XCTAssertEqual([1, 3, 3, 1], triangle.rows.last!) } - + func testFifthRow() { let triangle = PascalsTriangle(5) XCTAssertEqual([1, 4, 6, 4, 1], triangle.rows.last!) } - + func testTwentiethRow() { let triangle = PascalsTriangle(20) let expected = [ @@ -37,5 +37,5 @@ class PascalsTriangleTest: XCTestCase { ] XCTAssertEqual(expected, triangle.rows.last!) } - + } diff --git a/exercises/perfect-numbers/PerfectNumbersExample.swift b/exercises/perfect-numbers/PerfectNumbersExample.swift index b4ee8f8fe..129f1eb3d 100644 --- a/exercises/perfect-numbers/PerfectNumbersExample.swift +++ b/exercises/perfect-numbers/PerfectNumbersExample.swift @@ -1,11 +1,7 @@ -// Foundation not needed - - - enum NumberClassification { - case Perfect - case Abundant - case Deficient + case perfect + case abundant + case deficient } struct NumberClassifier { @@ -16,15 +12,15 @@ struct NumberClassifier { var classification: NumberClassification { switch (sum) { case let sum where sum == number : - return NumberClassification.Perfect + return NumberClassification.perfect case let sum where sum < number : - return NumberClassification.Deficient + return NumberClassification.deficient default: - return NumberClassification.Abundant - } + return NumberClassification.abundant + } } - func aliquotSum (input:Int)->Int { - return Array(1..<(input-1)).filter( {input % $0 == 0} ).reduce(0,combine: +) + func aliquotSum (_ input: Int) -> Int { + return Array(1..<(input-1)).filter({input % $0 == 0}).reduce(0, combine: +) } init(number: Int) { diff --git a/exercises/perfect-numbers/PerfectNumbersTest.swift b/exercises/perfect-numbers/PerfectNumbersTest.swift index bb42be95f..008c12cdd 100644 --- a/exercises/perfect-numbers/PerfectNumbersTest.swift +++ b/exercises/perfect-numbers/PerfectNumbersTest.swift @@ -1,34 +1,27 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class PerfectNumbersTest: XCTestCase { - - func testPerfect() { let numberClassifier = NumberClassifier(number: 6) - XCTAssertEqual([.Perfect],[numberClassifier.classification]) + XCTAssertEqual([.perfect], [numberClassifier.classification]) } - + func testPerfectAgain() { let numberClassifier = NumberClassifier(number: 28) - XCTAssertEqual([.Perfect],[numberClassifier.classification]) - - + XCTAssertEqual([.perfect], [numberClassifier.classification]) } - + func testDeficient() { let numberClassifier = NumberClassifier(number: 13) - XCTAssertEqual([.Deficient],[numberClassifier.classification]) - + XCTAssertEqual([.deficient], [numberClassifier.classification]) + } - + func testAbundant() { let numberClassifier = NumberClassifier(number: 12) - XCTAssertEqual([.Abundant],[numberClassifier.classification]) - - + XCTAssertEqual([.abundant], [numberClassifier.classification]) } - + } diff --git a/exercises/phone-number/PhoneNumberExample.swift b/exercises/phone-number/PhoneNumberExample.swift index fffab4a04..b55e8741d 100644 --- a/exercises/phone-number/PhoneNumberExample.swift +++ b/exercises/phone-number/PhoneNumberExample.swift @@ -1,21 +1,10 @@ -// Foundation not needed - - - private extension String { - subscript (range: Range) -> String { + subscript (range: CountableClosedRange) -> String { get { - #if swift(>=3.0) - let start = startIndex.advanced(by:range.startIndex) - let end = start.advanced(by:range.endIndex - range.startIndex) + let start = characters.index(startIndex, offsetBy: range.lowerBound) + let end = characters.index(start, offsetBy: range.upperBound - range.lowerBound) - #else - let start = startIndex.advancedBy(range.startIndex) - let end = start.advancedBy(range.endIndex - range.startIndex) - - #endif - - return self[start..=3.0) + import XCTest +#endif -import XCTest +class PhoneNumberTest: XCTestCase { - - -class PhoneNumberTest : XCTestCase { - func testValidWithTenDigits() { let startingNumber = "1234567890" let expected = "1234567890" @@ -18,35 +17,35 @@ class PhoneNumberTest : XCTestCase { let result = PhoneNumber(startingNumber) XCTAssertEqual(result.number, expected) } - + func testCleansNumberWithDots() { let startingNumber = "123.456.7890" let expected = "1234567890" let result = PhoneNumber(startingNumber) XCTAssertEqual(result.number, expected) } - + func testValidWithElevenDigitsAndFirstIsOne() { let startingNumber = "11234567890" let expected = "1234567890" let result = PhoneNumber(startingNumber) XCTAssertEqual(result.number, expected) } - + func testInvalidWhenElevenDigits() { let startingNumber = "21234567890" let expected = "0000000000" let result = PhoneNumber(startingNumber) XCTAssertEqual(result.number, expected) } - + func testInvalidWhenNineDigits() { let startingNumber = "123456789" let expected = "0000000000" let result = PhoneNumber(startingNumber) XCTAssertEqual(result.number, expected) } - + func testAreaCode() { let startingNumber = "1234567890" let expected = "123" @@ -54,19 +53,19 @@ class PhoneNumberTest : XCTestCase { let result = number.areaCode XCTAssertEqual(result, expected) } - + func testPrettyPrint() { let startingNumber = "1234567890" let expected = "(123) 456-7890" let number = PhoneNumber(startingNumber) XCTAssertEqual(String(number), expected) } - + func testPrettyPrintWithFullUSPhoneNumber() { let startingNumber = "11234567890" let expected = "(123) 456-7890" let number = PhoneNumber(startingNumber) XCTAssertEqual(String(number), expected) } - -} \ No newline at end of file + +} diff --git a/exercises/pig-latin/PigLatinExample.swift b/exercises/pig-latin/PigLatinExample.swift index b3b14168b..e50d02906 100644 --- a/exercises/pig-latin/PigLatinExample.swift +++ b/exercises/pig-latin/PigLatinExample.swift @@ -1,69 +1,51 @@ -// Foundation not needed - - - -private extension String{ - func substringFromIndexInt(indx:Int) -> String { - let index = self.startIndex.advancedBy(indx) - return self.substringFromIndex(index) +private extension String { + func substringFromIndexInt(_ indx: Int) -> String { + let index = self.characters.index(self.startIndex, offsetBy: indx) + return self.substring(from: index) } - func substringWithRangeInt(intRange:Range)->String{ - let start = self.startIndex.advancedBy(intRange.startIndex) - let end = self.startIndex.advancedBy(intRange.endIndex) - return self.substringWithRange(start..) -> String { + let start = self.characters.index(self.startIndex, offsetBy: intRange.lowerBound) + let end = self.characters.index(self.startIndex, offsetBy: intRange.upperBound) + return self.substring(with: start.. String { - return word.componentsSeparatedByString(" ").map{self.translateWord($0)}.joinWithSeparator(" ") - + static func translate (_ word: String) -> String { + return word.components(separatedBy: " ").map {self.translateWord($0)}.joined(separator: " ") } - - static func translateWord(word:String) -> String{ - - - func wordStartsWithPrefixes(word:String, prefixes:[String]) ->Bool{ - return 0 < prefixes.filter{word.hasPrefix($0)}.count - + + static func translateWord(_ word: String) -> String { + + func wordStartsWithPrefixes(_ word: String, prefixes: [String]) -> Bool { + return 0 < prefixes.filter {word.hasPrefix($0)}.count } - - func wordStartsWithVowelLike(word:String) ->Bool{ - return wordStartsWithPrefixes(word, prefixes: ["xr", "yt", "a", "e","i", "o","u" ]) + + func wordStartsWithVowelLike(_ word: String) -> Bool { + return wordStartsWithPrefixes(word, prefixes: ["xr", "yt", "a", "e", "i", "o", "u" ]) } - - func wordStartsWithConsonantAndQu(word:String) -> Bool{ - let index = word.startIndex.advancedBy(1) - return word.substringFromIndex(index).hasPrefix("qu") + + func wordStartsWithConsonantAndQu(_ word: String) -> Bool { + let index = word.characters.index(word.startIndex, offsetBy: 1) + return word.substring(from: index).hasPrefix("qu") } - - - if wordStartsWithVowelLike(word){return word + "ay"} - if wordStartsWithPrefixes(word, prefixes: ["thr", "sch"]){ - return (word.substringFromIndexInt(3) + word.substringWithRangeInt(0..<3) + "ay") } - - if wordStartsWithPrefixes(word, prefixes: ["ch", "qu", "th"]){ - return word.substringFromIndexInt(2) + - word.substringWithRangeInt(0..<2) + "ay" } - if wordStartsWithConsonantAndQu(word){ - return word.substringFromIndexInt(3) + - word.substringWithRangeInt(0..<1) + "quay"} + if wordStartsWithVowelLike(word) {return word + "ay"} + if wordStartsWithPrefixes(word, prefixes: ["thr", "sch"]) { + return (word.substringFromIndexInt(3) + word.substringWithRangeInt(0..<3) + "ay") } + + if wordStartsWithPrefixes(word, prefixes: ["ch", "qu", "th"]) { + return word.substringFromIndexInt(2) + + word.substringWithRangeInt(0..<2) + "ay" } + if wordStartsWithConsonantAndQu(word) { + return word.substringFromIndexInt(3) + + word.substringWithRangeInt(0..<1) + "quay"} return word.substringFromIndexInt(1) + word.substringWithRangeInt(0..<1) + "ay" - + } - - - - - -} \ No newline at end of file +} diff --git a/exercises/pig-latin/PigLatinTest.swift b/exercises/pig-latin/PigLatinTest.swift index e6084be43..250480490 100644 --- a/exercises/pig-latin/PigLatinTest.swift +++ b/exercises/pig-latin/PigLatinTest.swift @@ -1,69 +1,66 @@ +#if swift(>=3.0) + import XCTest +#endif -import XCTest - - - -class PigLatinTest : XCTestCase { - - +class PigLatinTest: XCTestCase { func testWordBeginningWithA() { XCTAssertEqual("appleay", PigLatin.translate("apple")) } - + func test_otherWordBeginningE() { XCTAssertEqual("earay", PigLatin.translate("ear")) } - + func testWordBeginningWithP() { XCTAssertEqual("igpay", PigLatin.translate("pig")) } - + func testWordBeginningWithK() { XCTAssertEqual("oalakay", PigLatin.translate("koala")) } - + func testWordBeginningWithCh() { XCTAssertEqual("airchay", PigLatin.translate("chair")) } - + func testWordBeginningWithQu() { XCTAssertEqual("eenquay", PigLatin.translate("queen")) } - + func testWordWithConsonantPrecedingQu() { XCTAssertEqual("aresquay", PigLatin.translate("square")) } - + func testWordBeginningWithTh() { XCTAssertEqual("erapythay", PigLatin.translate("therapy")) } - + func testWordBeginningWithThr() { XCTAssertEqual("ushthray", PigLatin.translate("thrush")) } - + func testWordBeginningWithSch() { XCTAssertEqual("oolschay", PigLatin.translate("school")) } - + func testWordBeginningWithYe() { XCTAssertEqual("ellowyay", PigLatin.translate("yellow")) } - + func testWordBeginningWithYt() { XCTAssertEqual("yttriaay", PigLatin.translate("yttria")) } - + func testWordBeginningWithXe() { XCTAssertEqual("enonxay", PigLatin.translate("xenon")) } - + func testWordBeginningWithXr() { XCTAssertEqual("xrayay", PigLatin.translate("xray")) } - + func testTranslatesPhrase() { XCTAssertEqual("ickquay astfay unray", PigLatin.translate("quick fast run")) } - -} \ No newline at end of file + +} diff --git a/exercises/poker/PokerExample.swift b/exercises/poker/PokerExample.swift index 9f4d4fcf1..e2878d6d0 100644 --- a/exercises/poker/PokerExample.swift +++ b/exercises/poker/PokerExample.swift @@ -1,50 +1,49 @@ - private extension String { - - func split(input: String)->[String] { - return self.componentsSeparatedByString(input) + + func split(_ input: String) -> [String] { + return self.components(separatedBy: input) } // Returns the Rank part of the card - func head()->String{ - return self.substringToIndex(self.endIndex.predecessor()) + func head() -> String { + return self.substring(to: self.characters.index(before: self.endIndex)) } // Return the Suit part of the card - func tail()->String{ - return self.substringFromIndex(self.endIndex.predecessor()) + func tail() -> String { + return self.substring(from: self.characters.index(before: self.endIndex)) } } -struct Poker{ - - static func bestHand(hands:[String])->String?{ - - var pokerHandsParsed:[PokerHand] = [] - - for each in hands{ +struct Poker { + + static func bestHand(_ hands: [String]) -> String? { + + var pokerHandsParsed: [PokerHand] = [] + + for each in hands { guard let pokerHand = PokerHand(each) else { return nil } pokerHandsParsed.append(pokerHand) } - - guard let topHand = (pokerHandsParsed.sort(>)).first, - let indexTop = pokerHandsParsed.indexOf(topHand) else {return nil} - + + guard let topHand = (pokerHandsParsed.sorted(isOrderedBefore: >)).first, + indexTop = pokerHandsParsed.index(of: topHand) else {return nil} + return hands[indexTop] - + } } -enum HandRank{ +enum HandRank { case highCard(PlayingCard) - case onePair(Rank,card1:Rank, card2:Rank, card3:Rank ) - case twoPair(high:Rank,low:Rank, highCard:PlayingCard) + case onePair(Rank, card1:Rank, card2:Rank, card3:Rank ) + case twoPair(high:Rank, low:Rank, highCard:PlayingCard) case threeOfAKind(three:Rank) case straight(high:Rank) case flush(Rank, Suit) case fullHouse(three:Rank) case fourOfAKind(four:Rank) - case straightFlush(Rank,Suit) - - func order()->Int{ + case straightFlush(Rank, Suit) + + func order() -> Int { switch self { case .highCard(_): return 1 case .onePair(_, card1: _, card2: _, card3: _): return 2 @@ -54,60 +53,60 @@ enum HandRank{ case flush(_, _): return 6 case fullHouse(three:_): return 7 case fourOfAKind(four:_): return 8 - case straightFlush(_,_): return 9 + case straightFlush(_, _): return 9 } } - - static func parsePairs(inputHand:PokerHand)->[(rank:Rank,count:Int)]{ + + static func parsePairs(_ inputHand: PokerHand)->[(rank: Rank, count: Int)] { let ranks = inputHand.hand.map({$0.rank}) let rankSet = Set(ranks) var toReturn = [Rank:Int]() - for each in ranks{ + for each in ranks { if rankSet.contains(each) { toReturn[each] = (toReturn[each] ?? 0) + 1 } } - let result = toReturn.map({key,value in return (rank:key,count:value)}).sort({ + let result = toReturn.map({key, value in return (rank:key, count:value)}).sorted(isOrderedBefore: { (one, two) in - return one.count == two.count ? one.rank > two.rank : one.count > two.count - }) + return one.count == two.count ? one.rank > two.rank : one.count > two.count + }) return result } - - static func isFlush(inputHand:PokerHand)->(bool:Bool,suit:Suit){ + + static func isFlush(_ inputHand: PokerHand)->(bool: Bool, suit: Suit) { let suits = inputHand.hand.map({$0.suit}) let first = suits[0] - for each in suits{ - if (first != each) { return (false,.None)} + for each in suits { + if (first != each) { return (false, .None)} } - return (true,first) + return (true, first) } - - static func isStraight(inputHand:PokerHand)->(bool:Bool, highest:Rank){ - let sorted = inputHand.hand.sort({$0.rank < $1.rank}) + + static func isStraight(_ inputHand: PokerHand)->(bool: Bool, highest: Rank) { + let sorted = inputHand.hand.sorted(isOrderedBefore: {$0.rank < $1.rank}) let first = sorted[0].rank.rawValue - for (index, each) in sorted.enumerate() { - if (each.rank.rawValue != index + first){ + for (index, each) in sorted.enumerated() { + if (each.rank.rawValue != index + first) { // checks for Ace as the lowest card - guard let aceIndex = inputHand.hand.indexOf({$0.rank.rawValue == 14})else {return (false, .Ace)} + guard let aceIndex = inputHand.hand.index(where: {$0.rank.rawValue == 14})else {return (false, .ace)} var replacedAced = inputHand.hand.map({$0.rank.rawValue}) replacedAced[aceIndex] = 1 // swaps ace value to lowest - replacedAced.sortInPlace() + replacedAced.sort() let firstVal = replacedAced[0] - for (idx,eachVal) in replacedAced.enumerate(){ - if (eachVal != firstVal + idx ) { return (false,.Ace) } + for (idx, eachVal) in replacedAced.enumerated() { + if (eachVal != firstVal + idx ) { return (false, .ace) } } } } let last = sorted[sorted.count - 1].rank - return (true,last) + return (true, last) } - - init(_ pokerHand:PokerHand){ + + init(_ pokerHand: PokerHand) { let pairs = HandRank.parsePairs(pokerHand) let (flush, flushSuit) = HandRank.isFlush(pokerHand) let (straight, straightRank) = HandRank.isStraight(pokerHand) - + //straightFlush if flush && straight { self = .straightFlush(straightRank, flushSuit) @@ -118,7 +117,7 @@ enum HandRank{ } else if pairs[0].count == 3 && pairs.count == 2 { self = .fullHouse(three: (pairs[0]).rank) //flush - }else if flush { + } else if flush { let r = (pairs[0]).rank self = .flush(r, flushSuit) //straight @@ -132,7 +131,7 @@ enum HandRank{ let r = (pairs[2]).rank let s = pokerHand.hand[4].suit self = .twoPair(high: (pairs[0]).rank, low: (pairs[1]).rank, - highCard:PlayingCard.init(rank: r, suit: s)) + highCard:PlayingCard.init(rank: r, suit: s)) //onePair } else if pairs[0].count == 2 && pairs.count == 4 { self = .onePair((pairs[0]).rank, card1: (pairs[1]).rank, card2: (pairs[2]).rank, card3: (pairs[3]).rank) @@ -147,39 +146,38 @@ enum HandRank{ extension HandRank : Equatable, Comparable {} -func ==(lhs: HandRank, rhs: HandRank) -> Bool { +func == (lhs: HandRank, rhs: HandRank) -> Bool { switch (lhs, rhs) { - //straightFlush(Rank,Suit) - case (HandRank.straightFlush(let lRank, let lSuit),HandRank.straightFlush(let rRank , let rSuit)): + //straightFlush(Rank,Suit) + case (HandRank.straightFlush(let lRank, let lSuit), HandRank.straightFlush(let rRank, let rSuit)): return lRank == rRank && lSuit == rSuit - //fourOfAKind(four:Rank) + //fourOfAKind(four:Rank) case (HandRank.fourOfAKind(four: let lFour), HandRank.fourOfAKind(four: let rFour)): return lFour == rFour - //fullHouse(three:Rank) + //fullHouse(three:Rank) case (HandRank.fullHouse(three: let lThree), HandRank.fullHouse(three: let rThree)): return lThree == rThree - //flush(Suit) - case (HandRank.flush(let lRank, let lSuit) - ,HandRank.flush(let rRank, let rSuit)): + //flush(Suit) + case (HandRank.flush(let lRank, let lSuit), HandRank.flush(let rRank, let rSuit)): return lSuit == rSuit && lRank == rRank - //straight(high:Rank) + //straight(high:Rank) case (HandRank.straight(high: let lRank), HandRank.straight(high: let rRank)): return lRank == rRank - //threeOfAKind(three:Rank) + //threeOfAKind(three:Rank) case (HandRank.threeOfAKind(three: let lRank), HandRank.threeOfAKind(three: let rRank)): return lRank == rRank - //twoPair(high:Rank,low:Rank, highCard:PlayingCard) - case (HandRank.twoPair(high: let lHigh, low: let lLow, highCard: let lCard),HandRank.twoPair(high: let rHigh, low: let rLow, highCard: let rCard)): + //twoPair(high:Rank,low:Rank, highCard:PlayingCard) + case (HandRank.twoPair(high: let lHigh, low: let lLow, highCard: let lCard), HandRank.twoPair(high: let rHigh, low: let rLow, highCard: let rCard)): return lHigh == rHigh && lLow == rLow && lCard == rCard - //onePair(Rank) + //onePair(Rank) case (HandRank.onePair(let lPairRank, card1: let lCard1, card2: let lCard2, card3: let lCard3), HandRank.onePair(let rPairRank, card1: let rCard1, card2: let rCard2, card3: let rCard3)): return lPairRank == rPairRank && lCard1 == rCard1 && lCard2 == rCard2 && lCard3 == rCard3 - //highCard(PlayingCard) + //highCard(PlayingCard) case (HandRank.highCard(let lCard), HandRank.highCard(let rCard)): return lCard == rCard default: @@ -187,108 +185,104 @@ func ==(lhs: HandRank, rhs: HandRank) -> Bool { } } -func <(lhs: HandRank, rhs: HandRank) -> Bool { +func < (lhs: HandRank, rhs: HandRank) -> Bool { switch (lhs, rhs) { case (_, _) where lhs == rhs: return false - - //straightFlush(Rank,Suit) - case (HandRank.straightFlush(let lRank, let lSuit),HandRank.straightFlush(let rRank , let rSuit)): + + //straightFlush(Rank,Suit) + case (HandRank.straightFlush(let lRank, let lSuit), HandRank.straightFlush(let rRank, let rSuit)): return lRank == rRank ? lSuit < rSuit : lRank < rRank - - //fourOfAKind(four:Rank) + + //fourOfAKind(four:Rank) case (HandRank.fourOfAKind(four: let lFour), HandRank.fourOfAKind(four: let rFour)): return lFour < rFour - - //fullHouse(three:Rank) + + //fullHouse(three:Rank) case (HandRank.fullHouse(three: let lRank), HandRank.fullHouse(three: let rRank)): return lRank < rRank - - //flush(Suit) - case (HandRank.flush(let lRank,let lSuit),HandRank.flush(let rRank, let rSuit)): + + //flush(Suit) + case (HandRank.flush(let lRank, let lSuit), HandRank.flush(let rRank, let rSuit)): return lRank == rRank ? lSuit < rSuit : lRank < rRank - - //straight(high:Rank) + + //straight(high:Rank) case (HandRank.straight(high: let lRank), HandRank.straight(high: let rRank)): return lRank < rRank - - //threeOfAKind(three:Rank) + + //threeOfAKind(three:Rank) case (HandRank.threeOfAKind(three: let lRank), HandRank.threeOfAKind(three: let rRank)): return lRank < rRank - - //twoPair(high:Rank,low:Rank, highCard:PlayingCard) - case (HandRank.twoPair(high: let lHigh, low: let lLow, highCard: let lCard),HandRank.twoPair(high: let rHigh, low: let rLow, highCard: let rCard)): + + //twoPair(high:Rank,low:Rank, highCard:PlayingCard) + case (HandRank.twoPair(high: let lHigh, low: let lLow, highCard: let lCard), HandRank.twoPair(high: let rHigh, low: let rLow, highCard: let rCard)): if lHigh == rHigh && lLow == rLow { return lCard < rCard } else { return lHigh < rHigh } - - //onePair(Rank) + + //onePair(Rank) case (HandRank.onePair(let lPairRank, card1: let lCard1, card2: let lCard2, card3: let lCard3), HandRank.onePair(let rPairRank, card1: let rCard1, card2: let rCard2, card3: let rCard3)): return lPairRank == rPairRank ? (lCard1 == rCard1 ? (lCard2 == rCard2 ? lCard3 < rCard3 :lCard2 < rCard2):lCard1 < rCard1):lPairRank < rPairRank - - //highCard(PlayingCard) + + //highCard(PlayingCard) case (HandRank.highCard(let lCard), HandRank.highCard(let rCard)): return lCard < rCard - + default: return lhs.order() < rhs.order() } - + } -struct PokerHand{ - let hand:[PlayingCard] - - func handRank()->HandRank{ +struct PokerHand { + let hand: [PlayingCard] + + func handRank() -> HandRank { return HandRank(self) } - - init?(_ stringHand:String){ - - var handParsed:[PlayingCard] = [] - - for each in stringHand.split(" "){ + + init?(_ stringHand: String) { + + var handParsed: [PlayingCard] = [] + + for each in stringHand.split(" ") { guard let card = PlayingCard(each) else {return nil} handParsed.append(card) } - + if handParsed.count == 5 {self.hand = handParsed } else {return nil} } } - - extension PokerHand : Equatable, Comparable {} -func ==(lhs: PokerHand, rhs: PokerHand) -> Bool{ +func == (lhs: PokerHand, rhs: PokerHand) -> Bool { return lhs.hand == rhs.hand } -func <(lhs: PokerHand, rhs: PokerHand) -> Bool { +func < (lhs: PokerHand, rhs: PokerHand) -> Bool { return lhs.handRank() < rhs.handRank() } - - struct PlayingCard { let rank: Rank let suit: Suit - + init(rank: Rank, suit: Suit) { self.rank = rank self.suit = suit } - - init?(_ stringInput:String){ - + + init?(_ stringInput: String) { + guard let rank = Rank(stringInput.head()), - let suit = Suit(stringInput.tail()) else { return nil} - + suit = Suit(stringInput.tail()) else { return nil} + self.rank = rank self.suit = suit } @@ -296,23 +290,21 @@ struct PlayingCard { extension PlayingCard : Equatable, Comparable {} -func ==(lhs: PlayingCard, rhs: PlayingCard) -> Bool{ +func == (lhs: PlayingCard, rhs: PlayingCard) -> Bool { return lhs.rank == rhs.rank && lhs.suit == rhs.suit } -func <(lhs: PlayingCard, rhs: PlayingCard) -> Bool { +func < (lhs: PlayingCard, rhs: PlayingCard) -> Bool { return lhs.rank == rhs.rank ? lhs.suit < rhs.suit : lhs.rank < rhs.rank } +enum Rank: Int { + case two = 2 + case three, four, five, six, seven, eight, nine, ten + case jack, queen, king, ace - -enum Rank : Int { - case Two = 2 - case Three, Four, Five, Six, Seven, Eight, Nine, Ten - case Jack, Queen, King, Ace - - init?(_ rank:String){ + init?(_ rank: String) { var rankInt = 0 - switch rank{ + switch rank { case "A": rankInt = 14 case "J": rankInt = 11 case "Q": rankInt = 12 @@ -326,9 +318,9 @@ enum Rank : Int { enum Suit: String { case Spades, Hearts, Diamonds, Clubs case None - - init?(_ suit:String){ - + + init?(_ suit: String) { + switch suit { case "♡": self = .Hearts case "♢": self = .Diamonds @@ -341,7 +333,7 @@ enum Suit: String { extension Rank : Comparable {} -func <(lhs: Rank, rhs: Rank) -> Bool { +func < (lhs: Rank, rhs: Rank) -> Bool { switch (lhs, rhs) { case (_, _) where lhs == rhs: return false @@ -352,15 +344,15 @@ func <(lhs: Rank, rhs: Rank) -> Bool { extension Suit: Comparable {} -func <(lhs: Suit, rhs: Suit) -> Bool { +func < (lhs: Suit, rhs: Suit) -> Bool { switch (lhs, rhs) { case (_, _) where lhs == rhs: return false case (.Spades, _), - (.Hearts, .Diamonds), (.Hearts, .Clubs), - (.Diamonds, .Clubs): + (.Hearts, .Diamonds), (.Hearts, .Clubs), + (.Diamonds, .Clubs): return false default: return true } -} \ No newline at end of file +} diff --git a/exercises/poker/PokerTest.swift b/exercises/poker/PokerTest.swift index fa8d1480e..48dc96d1b 100644 --- a/exercises/poker/PokerTest.swift +++ b/exercises/poker/PokerTest.swift @@ -1,284 +1,284 @@ -import XCTest +#if swift(>=3.0) + import XCTest +#endif class PokerTest: XCTestCase { - - var validTestCases:[(name: String, hands:[String], best:String)] = [] - var invalidTestCases:[(name: String, hand:String)] = [] - - func testInvalidCases(){ - for each in invalidTestCases{ - XCTAssertNil(PokerHand(each.hand), "\(each.name)") + + var validTestCases:[(name: String, hands: [String], best: String)] = [] + var invalidTestCases:[(name: String, hand: String)] = [] + + func testInvalidCases() { + for each in invalidTestCases { + XCTAssertNil(PokerHand(each.hand), "\(each.name)") } } - + func testAllValid() { - for each in validTestCases{ - XCTAssertEqual(Poker.bestHand(each.hands), each.best, "\(each.name)") + for each in validTestCases { + XCTAssertEqual(Poker.bestHand(each.hands), each.best, "\(each.name)") } } - + override func setUp() { super.setUp() - - validTestCases = [ - ( - name: "single hand is always best", - hands: ["3♡ 10♢ 7♧ 8♤ A♢"], - best: "3♡ 10♢ 7♧ 8♤ A♢" - ), - ( - name: "highest card", - hands: ["3♢ 2♢ 5♤ 6♤ 9♡", "3♡ 2♡ 5♧ 6♢ 10♡"], - best: "3♡ 2♡ 5♧ 6♢ 10♡" - ), - ( - name: "One pair", - hands: ["3♢ 2♢ 5♤ 6♤ 9♡", "3♡ 3♤ 5♧ 6♢ 9♢"], - best: "3♡ 3♤ 5♧ 6♢ 9♢" - ), - ( - name: "pair beats lower", - hands: ["4♢ 3♤ 4♤ J♤ K♤", "A♡ K♡ J♢ 10♧ 9♡"], - best: "4♢ 3♤ 4♤ J♤ K♤" - ), - ( - name: "best pair", - hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "3♢ 3♡ 5♤ 6♤ 9♡"], - best: "4♡ 2♡ 5♧ 4♢ 10♡" - ), - ( - name: "best pair with same pair and highest cards", - hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "4♤ 4♧ 5♡ 10♢ 3♡"], - best: "4♤ 4♧ 5♡ 10♢ 3♡" - ), - ( - name: "two pair beats lower", - hands: [ - "4♢ 3♤ 4♤ J♤ K♤", - "A♡ K♡ J♢ 10♧ 9♡", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "2♢ 8♡ 5♢ 2♡ 8♧" - ), - ( - name: "best two pair", - hands: [ - "4♢ J♧ 4♤ J♤ K♤", - "A♡ K♡ J♢ 10♧ 9♡", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "4♢ J♧ 4♤ J♤ K♤" - ), - ( - name: "best two pair with equal highest pair", - hands: [ - "4♢ J♧ 4♤ J♤ K♤", - "A♡ K♡ J♢ 10♧ 9♡", - "3♢ J♡ 5♢ 3♡ J♢", - ], - best: "4♢ J♧ 4♤ J♤ K♤" - ), - ( - name: "best two pair with equal pairs", - hands: [ - "4♢ J♧ 4♤ J♤ 2♤", - "A♡ K♡ J♢ 10♧ 9♡", - "4♧ J♡ 5♢ 4♡ J♢", - ], - best: "4♧ J♡ 5♢ 4♡ J♢" - ), - ( - name: "full house", - hands: [ - "4♢ 3♤ 4♤ J♤ K♤", - "A♡ K♡ J♢ 10♧ 9♡", - "3♡ 8♡ 3♢ 3♧ 8♧", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "3♡ 8♡ 3♢ 3♧ 8♧" - ), - ( - name: "best three of a kind", - hands: [ - "4♢ 3♤ 4♤ J♤ 4♡", - "A♡ K♡ J♢ 10♧ 9♡", - "3♢ 8♡ 3♡ 3♧ 9♧", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "4♢ 3♤ 4♤ J♤ 4♡" - ), - ( - name: "straight beats lower", - hands: [ - "4♢ 3♤ 4♤ J♤ K♤", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♡ 8♡ 3♢ 3♧ 9♧", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "Q♡ K♡ J♢ 10♧ 9♡" - ), - ( - name: "straight includes ace as one", - hands: [ - "4♢ 3♤ 4♤ J♤ K♤", - "2♤ 3♡ A♤ 5♤ 4♤", - "3♢ 8♡ 3♡ 3♧ 9♧", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "2♤ 3♡ A♤ 5♤ 4♤" - ), - ( - name: "best straight", - hands: [ - "4♢ 3♤ 4♤ J♤ K♤", - "Q♡ K♡ J♢ 10♧ 9♡", - "A♢ K♧ 10♢ J♢ Q♢", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "A♢ K♧ 10♢ J♢ Q♢" - ), - ( - name: "flush beats lower", - hands: [ - "4♤ 3♤ 8♤ J♤ K♤", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♢ 8♡ 3♢ 3♧ 9♧", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "4♤ 3♤ 8♤ J♤ K♤" - ), - ( - name: "best flush", - hands: [ - "4♤ 3♤ 8♤ J♤ K♤", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♢ 8♢ A♢ 2♢ 7♢", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "3♢ 8♢ A♢ 2♢ 7♢" - ), - ( - name: "full house beats lower", - hands: [ - "4♤ 3♤ 8♤ J♤ K♤", - "2♢ 8♡ 8♢ 2♡ 8♧", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♡ A♡ 3♢ 3♧ A♧", - ], - best: "2♢ 8♡ 8♢ 2♡ 8♧" - ), - ( - name: "best full house", - hands: [ - "4♤ 3♤ 8♤ J♤ K♤", - "2♢ 8♡ 8♢ 2♡ 8♧", - "5♡ 5♢ A♤ 5♧ A♢", - "3♡ A♡ 3♢ 3♧ A♧", - ], - best: "2♢ 8♡ 8♢ 2♡ 8♧" - ), - ( - name: "four of a kind beats lower", - hands: [ - "4♤ 5♤ 8♤ J♤ K♤", - "2♢ 8♡ 8♢ 2♡ 8♧", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♢ 3♡ 3♤ 3♧ A♧", - ], - best: "3♢ 3♡ 3♤ 3♧ A♧" - ), - ( - name: "best four of a kind", - hands: [ - "4♤ 5♤ 8♤ J♤ K♤", - "2♢ 2♧ 8♢ 2♡ 2♤", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♢ 3♡ 3♤ 3♧ A♧", - ], - best: "3♢ 3♡ 3♤ 3♧ A♧" - ), - ( - name: "straight flush beats lower", - hands: [ - "4♤ 4♢ 4♡ 4♧ K♤", - "2♢ 8♡ 8♢ 2♡ 8♧", - "Q♡ K♡ 8♡ 10♡ 9♡", - "2♤ 3♤ A♤ 5♤ 4♤", - ], - best: "2♤ 3♤ A♤ 5♤ 4♤" - ), - ( - name: "best straight flush is royal flush", - hands: [ - "4♤ 5♤ 8♤ J♤ K♤", - "2♢ 8♡ 8♢ 2♡ 8♧", - "Q♡ K♡ J♡ 10♡ 9♡", - "Q♢ K♢ J♢ 10♢ A♢", - ], - best: "Q♢ K♢ J♢ 10♢ A♢" - ), - ( - name: "tie for best pair: brake tide by suit", - hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "4♧ 10♢ 5♤ 2♤ 4♤"], - best: "4♡ 2♡ 5♧ 4♢ 10♡" - ), - ( - name: "tie of three: brake tide by suit", - hands: [ - "A♡ 2♡ 3♡ 4♡ 5♡", - "A♤ 2♤ 3♤ 4♤ 5♤", - "5♧ 4♧ 3♧ 2♧ A♧", - "A♢ 2♢ 6♢ 4♢ 5♢", - ], - best: "A♤ 2♤ 3♤ 4♤ 5♤" - ), - ] - - invalidTestCases = - [ - ( - name: "1 is an invalid card rank", - hand: "1♢ 2♡ 3♡ 4♡ 5♡" - ), - ( - name: "15 is an invalid card rank", - hand: "15♢ 2♡ 3♡ 4♡ 5♡" - ), - ( - name: "too few cards", - hand: "2♡ 3♡ 4♡ 5♡" - ), - ( - name: "too many cards", - hand: "2♡ 3♡ 4♡ 5♡ 6♡ 7♡" - ), - ( - name: "lack of rank", - hand: "11♢ 2♡ ♡ 4♡ 5♡" - ), - ( - name: "lack of suit", - hand: "2♡ 3♡ 4 5♡ 7♡" - ), - ( - name: "H is an invalid suit", - hand: "2♡ 3♡ 4H 5♡ 7♡" - ), - ( - name: "♥ is an invalid suit", - hand: "2♡ 3♡ 4♥ 5♡ 7♡" - ), - ( - name: "lack of spacing", - hand: "2♡ 3♡ 5♡7♡ 8♡" - ), - ( - name: "double suits after rank", - hand: "2♡ 3♡ 5♡♡ 8♡ 9♡" - ), - ] - + + validTestCases = [ + ( + name: "single hand is always best", + hands: ["3♡ 10♢ 7♧ 8♤ A♢"], + best: "3♡ 10♢ 7♧ 8♤ A♢" + ), + ( + name: "highest card", + hands: ["3♢ 2♢ 5♤ 6♤ 9♡", "3♡ 2♡ 5♧ 6♢ 10♡"], + best: "3♡ 2♡ 5♧ 6♢ 10♡" + ), + ( + name: "One pair", + hands: ["3♢ 2♢ 5♤ 6♤ 9♡", "3♡ 3♤ 5♧ 6♢ 9♢"], + best: "3♡ 3♤ 5♧ 6♢ 9♢" + ), + ( + name: "pair beats lower", + hands: ["4♢ 3♤ 4♤ J♤ K♤", "A♡ K♡ J♢ 10♧ 9♡"], + best: "4♢ 3♤ 4♤ J♤ K♤" + ), + ( + name: "best pair", + hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "3♢ 3♡ 5♤ 6♤ 9♡"], + best: "4♡ 2♡ 5♧ 4♢ 10♡" + ), + ( + name: "best pair with same pair and highest cards", + hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "4♤ 4♧ 5♡ 10♢ 3♡"], + best: "4♤ 4♧ 5♡ 10♢ 3♡" + ), + ( + name: "two pair beats lower", + hands: [ + "4♢ 3♤ 4♤ J♤ K♤", + "A♡ K♡ J♢ 10♧ 9♡", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "2♢ 8♡ 5♢ 2♡ 8♧" + ), + ( + name: "best two pair", + hands: [ + "4♢ J♧ 4♤ J♤ K♤", + "A♡ K♡ J♢ 10♧ 9♡", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "4♢ J♧ 4♤ J♤ K♤" + ), + ( + name: "best two pair with equal highest pair", + hands: [ + "4♢ J♧ 4♤ J♤ K♤", + "A♡ K♡ J♢ 10♧ 9♡", + "3♢ J♡ 5♢ 3♡ J♢", + ], + best: "4♢ J♧ 4♤ J♤ K♤" + ), + ( + name: "best two pair with equal pairs", + hands: [ + "4♢ J♧ 4♤ J♤ 2♤", + "A♡ K♡ J♢ 10♧ 9♡", + "4♧ J♡ 5♢ 4♡ J♢", + ], + best: "4♧ J♡ 5♢ 4♡ J♢" + ), + ( + name: "full house", + hands: [ + "4♢ 3♤ 4♤ J♤ K♤", + "A♡ K♡ J♢ 10♧ 9♡", + "3♡ 8♡ 3♢ 3♧ 8♧", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "3♡ 8♡ 3♢ 3♧ 8♧" + ), + ( + name: "best three of a kind", + hands: [ + "4♢ 3♤ 4♤ J♤ 4♡", + "A♡ K♡ J♢ 10♧ 9♡", + "3♢ 8♡ 3♡ 3♧ 9♧", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "4♢ 3♤ 4♤ J♤ 4♡" + ), + ( + name: "straight beats lower", + hands: [ + "4♢ 3♤ 4♤ J♤ K♤", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♡ 8♡ 3♢ 3♧ 9♧", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "Q♡ K♡ J♢ 10♧ 9♡" + ), + ( + name: "straight includes ace as one", + hands: [ + "4♢ 3♤ 4♤ J♤ K♤", + "2♤ 3♡ A♤ 5♤ 4♤", + "3♢ 8♡ 3♡ 3♧ 9♧", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "2♤ 3♡ A♤ 5♤ 4♤" + ), + ( + name: "best straight", + hands: [ + "4♢ 3♤ 4♤ J♤ K♤", + "Q♡ K♡ J♢ 10♧ 9♡", + "A♢ K♧ 10♢ J♢ Q♢", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "A♢ K♧ 10♢ J♢ Q♢" + ), + ( + name: "flush beats lower", + hands: [ + "4♤ 3♤ 8♤ J♤ K♤", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♢ 8♡ 3♢ 3♧ 9♧", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "4♤ 3♤ 8♤ J♤ K♤" + ), + ( + name: "best flush", + hands: [ + "4♤ 3♤ 8♤ J♤ K♤", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♢ 8♢ A♢ 2♢ 7♢", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "3♢ 8♢ A♢ 2♢ 7♢" + ), + ( + name: "full house beats lower", + hands: [ + "4♤ 3♤ 8♤ J♤ K♤", + "2♢ 8♡ 8♢ 2♡ 8♧", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♡ A♡ 3♢ 3♧ A♧", + ], + best: "2♢ 8♡ 8♢ 2♡ 8♧" + ), + ( + name: "best full house", + hands: [ + "4♤ 3♤ 8♤ J♤ K♤", + "2♢ 8♡ 8♢ 2♡ 8♧", + "5♡ 5♢ A♤ 5♧ A♢", + "3♡ A♡ 3♢ 3♧ A♧", + ], + best: "2♢ 8♡ 8♢ 2♡ 8♧" + ), + ( + name: "four of a kind beats lower", + hands: [ + "4♤ 5♤ 8♤ J♤ K♤", + "2♢ 8♡ 8♢ 2♡ 8♧", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♢ 3♡ 3♤ 3♧ A♧", + ], + best: "3♢ 3♡ 3♤ 3♧ A♧" + ), + ( + name: "best four of a kind", + hands: [ + "4♤ 5♤ 8♤ J♤ K♤", + "2♢ 2♧ 8♢ 2♡ 2♤", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♢ 3♡ 3♤ 3♧ A♧", + ], + best: "3♢ 3♡ 3♤ 3♧ A♧" + ), + ( + name: "straight flush beats lower", + hands: [ + "4♤ 4♢ 4♡ 4♧ K♤", + "2♢ 8♡ 8♢ 2♡ 8♧", + "Q♡ K♡ 8♡ 10♡ 9♡", + "2♤ 3♤ A♤ 5♤ 4♤", + ], + best: "2♤ 3♤ A♤ 5♤ 4♤" + ), + ( + name: "best straight flush is royal flush", + hands: [ + "4♤ 5♤ 8♤ J♤ K♤", + "2♢ 8♡ 8♢ 2♡ 8♧", + "Q♡ K♡ J♡ 10♡ 9♡", + "Q♢ K♢ J♢ 10♢ A♢", + ], + best: "Q♢ K♢ J♢ 10♢ A♢" + ), + ( + name: "tie for best pair: brake tide by suit", + hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "4♧ 10♢ 5♤ 2♤ 4♤"], + best: "4♡ 2♡ 5♧ 4♢ 10♡" + ), + ( + name: "tie of three: brake tide by suit", + hands: [ + "A♡ 2♡ 3♡ 4♡ 5♡", + "A♤ 2♤ 3♤ 4♤ 5♤", + "5♧ 4♧ 3♧ 2♧ A♧", + "A♢ 2♢ 6♢ 4♢ 5♢", + ], + best: "A♤ 2♤ 3♤ 4♤ 5♤" + ), + ] + + invalidTestCases = + [ + ( + name: "1 is an invalid card rank", + hand: "1♢ 2♡ 3♡ 4♡ 5♡" + ), + ( + name: "15 is an invalid card rank", + hand: "15♢ 2♡ 3♡ 4♡ 5♡" + ), + ( + name: "too few cards", + hand: "2♡ 3♡ 4♡ 5♡" + ), + ( + name: "too many cards", + hand: "2♡ 3♡ 4♡ 5♡ 6♡ 7♡" + ), + ( + name: "lack of rank", + hand: "11♢ 2♡ ♡ 4♡ 5♡" + ), + ( + name: "lack of suit", + hand: "2♡ 3♡ 4 5♡ 7♡" + ), + ( + name: "H is an invalid suit", + hand: "2♡ 3♡ 4H 5♡ 7♡" + ), + ( + name: "♥ is an invalid suit", + hand: "2♡ 3♡ 4♥ 5♡ 7♡" + ), + ( + name: "lack of spacing", + hand: "2♡ 3♡ 5♡7♡ 8♡" + ), + ( + name: "double suits after rank", + hand: "2♡ 3♡ 5♡♡ 8♡ 9♡" + ), + ] + } - - } diff --git a/exercises/prime-factors/PrimeFactorsExample.swift b/exercises/prime-factors/PrimeFactorsExample.swift index 5f2c0ea2b..9c6211f0b 100644 --- a/exercises/prime-factors/PrimeFactorsExample.swift +++ b/exercises/prime-factors/PrimeFactorsExample.swift @@ -1,21 +1,16 @@ -// Foundation not needed +struct PrimeFactors { + var number: Int64 - - -struct PrimeFactors{ - - var number:Int64 - var toArray = [Int64]() - - private func primesFor( number:Int64)->[Int64]{ + + private func primesFor( _ number: Int64) -> [Int64] { var number = number var primes = [Int64]() - var divisor:Int64 = 2 - - while (number > 1){ - while (number % divisor == 0){ + var divisor: Int64 = 2 + + while (number > 1) { + while (number % divisor == 0) { primes.append(divisor) number /= divisor } @@ -23,14 +18,10 @@ struct PrimeFactors{ } return primes } - - init(_ value:Int64){ - self.number = value - self.toArray = primesFor(value) - - } -} - - + init(_ value: Int64) { + self.number = value + self.toArray = primesFor(value) + } +} diff --git a/exercises/prime-factors/PrimeFactorsTest.swift b/exercises/prime-factors/PrimeFactorsTest.swift index 7f570c672..d87bb9291 100644 --- a/exercises/prime-factors/PrimeFactorsTest.swift +++ b/exercises/prime-factors/PrimeFactorsTest.swift @@ -1,55 +1,51 @@ -import XCTest - - - +#if swift(>=3.0) + import XCTest +#endif class PrimeFactorsTest: XCTestCase { - + func test1() { XCTAssertEqual([], PrimeFactors(1).toArray) } - + func test2() { - XCTAssertEqual([2] , PrimeFactors(2).toArray) + XCTAssertEqual([2], PrimeFactors(2).toArray) } - + func test3() { XCTAssertEqual([3], PrimeFactors(3).toArray) } - + func test4() { XCTAssertEqual([2, 2], PrimeFactors(4).toArray) } - + func test6() { XCTAssertEqual([2, 3], PrimeFactors(6).toArray) } - + func test8() { XCTAssertEqual([2, 2, 2], PrimeFactors(8).toArray) } - + func test9() { XCTAssertEqual([3, 3], PrimeFactors(9).toArray) } - + func test27() { XCTAssertEqual([3, 3, 3], PrimeFactors(27).toArray) } - + func test625() { XCTAssertEqual([5, 5, 5, 5], PrimeFactors(625).toArray) } - + func test901255() { XCTAssertEqual([5, 17, 23, 461], PrimeFactors(901_255).toArray) } - + func test93819012551() { XCTAssertEqual([11, 9539, 894_119], PrimeFactors(93_819_012_551).toArray) } - - - -} +} diff --git a/exercises/pythagorean-triplet/PythagoreanTripletExample.swift b/exercises/pythagorean-triplet/PythagoreanTripletExample.swift index f481e23f7..f11519fed 100644 --- a/exercises/pythagorean-triplet/PythagoreanTripletExample.swift +++ b/exercises/pythagorean-triplet/PythagoreanTripletExample.swift @@ -1,41 +1,39 @@ import Darwin +struct Triplet { + var a: Int, b: Int, c: Int = 0 -struct Triplet { - - var a:Int, b:Int, c:Int = 0 - - init(_ a:Int, _ b:Int, _ c:Int){ + init(_ a: Int, _ b: Int, _ c: Int) { self.a = a self.b = b self.c = c } - - var sum:Int{return a + b + c } - - var product:Int{return a * b * c } - - var isPythagorean:Bool{return pow(Double(a), 2) + pow(Double(b), 2) == pow(Double(c), 2)} - - static func Where(minFactor:Int = 1, maxFactor:Int, sum:Int = 0)->[Triplet]{ - - func shouldIncludeTriplet(sum:Int, triplet:Triplet)-> Bool { + + var sum: Int {return a + b + c } + + var product: Int {return a * b * c } + + var isPythagorean: Bool {return pow(Double(a), 2) + pow(Double(b), 2) == pow(Double(c), 2)} + + static func Where(_ minFactor: Int = 1, maxFactor: Int, sum: Int = 0) -> [Triplet] { + + func shouldIncludeTriplet(_ sum: Int, triplet: Triplet) -> Bool { return triplet.isPythagorean && (sum == 0 || triplet.sum == sum) } - + var triplets = [Triplet]() for i in minFactor ..< maxFactor - 1 { for j in i + 1 ..< maxFactor { for k in j + 1 ... maxFactor { let triplet = Triplet(i, j, k) - if shouldIncludeTriplet(sum, triplet: triplet){ + if shouldIncludeTriplet(sum, triplet: triplet) { triplets.append(triplet) } } } } - return triplets; + return triplets } - + } diff --git a/exercises/pythagorean-triplet/PythagoreanTripletTest.swift b/exercises/pythagorean-triplet/PythagoreanTripletTest.swift index 1b88a09e9..a2d5071da 100644 --- a/exercises/pythagorean-triplet/PythagoreanTripletTest.swift +++ b/exercises/pythagorean-triplet/PythagoreanTripletTest.swift @@ -1,44 +1,39 @@ - -import XCTest - - - +#if swift(>=3.0) + import XCTest +#endif class PythagoreanTripletTest: XCTestCase { func testSum() { XCTAssertEqual(12, Triplet(3, 4, 5).sum) } - + func testProduct() { XCTAssertEqual(60, Triplet(3, 4, 5).product) } - + func testPythagorean() { XCTAssertTrue(Triplet(3, 4, 5).isPythagorean) } - + func testNotPythagorean() { XCTAssertTrue(!Triplet(5, 6, 7).isPythagorean) } - + func testTripletsUpTo10() { let triplets = Triplet.Where(maxFactor: 10) - let products = triplets.map{$0.product}.sort(<) + let products = triplets.map {$0.product}.sorted(isOrderedBefore: <) XCTAssertEqual([60, 480], products) } - + func testTripletsFrom11UpTo20() { let triplets = Triplet.Where(11, maxFactor: 20) - let products = triplets.map{$0.product}.sort(<) + let products = triplets.map {$0.product}.sorted(isOrderedBefore: <) XCTAssertEqual([3840], products) } - + func testTripletsWhereSumX() { let triplets = Triplet.Where( maxFactor: 100, sum: 180) - let products = triplets.map{$0.product}.sort(<) + let products = triplets.map {$0.product}.sorted(isOrderedBefore: <) XCTAssertEqual([118_080, 168_480, 202_500], products) } - - } - diff --git a/exercises/queen-attack/QueenAttackExample.swift b/exercises/queen-attack/QueenAttackExample.swift index 92111dc8e..fee86dc82 100644 --- a/exercises/queen-attack/QueenAttackExample.swift +++ b/exercises/queen-attack/QueenAttackExample.swift @@ -1,30 +1,16 @@ -// Foundation not needed - - - struct Queens { - - #if swift(>=3.0) enum InitError: ErrorProtocol { - case SameSpace - case IncorrectNumberOfCoordinates - case InvalidCoordinates + case sameSpace + case incorrectNumberOfCoordinates + case invalidCoordinates } - #else - enum InitError: ErrorType { - case SameSpace - case IncorrectNumberOfCoordinates - case InvalidCoordinates - } - #endif - - + let white: [Int] let black: [Int] var canAttack: Bool { return onHorizontal || onVertical || onDiagonal } - + private var onHorizontal: Bool { return white[0] == black[0] } @@ -34,55 +20,40 @@ struct Queens { private var onDiagonal: Bool { return abs(black[1] - black[0]) == abs(white[1] - white[0]) } - + init(white: [Int] = [0, 3], black: [Int] = [7, 3]) throws { guard white.count == 2 && black.count == 2 else { - throw InitError.IncorrectNumberOfCoordinates + throw InitError.incorrectNumberOfCoordinates } - + for number in white + black { guard number >= 0 && number <= 7 else { - throw InitError.InvalidCoordinates + throw InitError.invalidCoordinates } } - + guard white != black else { - throw InitError.SameSpace + throw InitError.sameSpace } - + self.white = white self.black = black } - + } extension Queens: CustomStringConvertible { var description: String { - #if swift(>=3.0) - let row = [String](repeating: "_", count: 8) - var board = [[String]](repeating: row, count: 8) - #else - let row = [String](count: 8, repeatedValue: "_") - var board = [[String]](count: 8, repeatedValue: row) - - #endif - + let row = [String](repeating: "_", count: 8) + var board = [[String]](repeating: row, count: 8) + board[white[0]][white[1]] = "W" board[black[0]][black[1]] = "B" - + var rows = [String]() - #if swift(>=3.0) - - for row in board { - rows.append(row.joined(separator: " ")) - } - return rows.joined(separator: "\n") - #else - for row in board { - rows.append(row.joinWithSeparator(" ")) - } - return rows.joinWithSeparator("\n") - #endif - + for row in board { + rows.append(row.joined(separator: " ")) + } + return rows.joined(separator: "\n") } -} \ No newline at end of file +} diff --git a/exercises/queen-attack/QueenAttackTest.swift b/exercises/queen-attack/QueenAttackTest.swift index ad0a538dc..cde5a8fa7 100644 --- a/exercises/queen-attack/QueenAttackTest.swift +++ b/exercises/queen-attack/QueenAttackTest.swift @@ -1,150 +1,150 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class QueenAttackTest: XCTestCase { - + func testDefaultPositions() { let queens = try! Queens() XCTAssertEqual([0, 3], queens.white) XCTAssertEqual([7, 3], queens.black) } - + func testSpecificPlacement() { let queens = try! Queens(white: [3, 7], black: [6, 1]) XCTAssertEqual([3, 7], queens.white) XCTAssertEqual([6, 1], queens.black) } - + func testMultipleBoardsSimultaneously() { let queens1 = try! Queens(white: [3, 7], black: [6, 1]) let queens2 = try! Queens(white: [5, 4], black: [7, 7]) - + XCTAssertEqual([3, 7], queens1.white) XCTAssertEqual([6, 1], queens1.black) XCTAssertEqual([5, 4], queens2.white) XCTAssertEqual([7, 7], queens2.black) } - + func testIncorrectNumberOfCoordinates() { var throwsIncorrectNumberOfCoordinates = false - + defer { XCTAssertTrue(throwsIncorrectNumberOfCoordinates) } - + do { let _ = try Queens(white: [1, 2, 3], black: [4, 5]) - } catch Queens.InitError.IncorrectNumberOfCoordinates { + } catch Queens.InitError.incorrectNumberOfCoordinates { throwsIncorrectNumberOfCoordinates = true } catch { return } } - + func testInvalidCoordinates() { var throwsInvalidCoordinates = false - + defer { XCTAssertTrue(throwsInvalidCoordinates) } - + do { let _ = try Queens(white: [-3, 0], black: [2, 481]) - } catch Queens.InitError.InvalidCoordinates { + } catch Queens.InitError.invalidCoordinates { throwsInvalidCoordinates = true } catch { return } } - + func testCannotOccupySameSpace() { var throwsSameSpaceError = false - + defer { XCTAssertTrue(throwsSameSpaceError) } - + do { let _ = try Queens(white: [2, 4], black: [2, 4]) - } catch Queens.InitError.SameSpace { + } catch Queens.InitError.sameSpace { throwsSameSpaceError = true } catch { return } } - + func testStringRepresentation() { let queens = try! Queens(white: [2, 4], black: [6, 6]) let board = "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ W _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ B _\n" + - "_ _ _ _ _ _ _ _" + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ W _ _ _\n" + + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ _ _ B _\n" + + "_ _ _ _ _ _ _ _" XCTAssertEqual(board, queens.description) } func testAnotherStringRepresentation() { let queens = try! Queens(white: [7, 1], black: [0, 0]) let board = "B _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ W _ _ _ _ _ _" + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ _ _ _ _\n" + + "_ W _ _ _ _ _ _" XCTAssertEqual(board, queens.description) } - + func testYetAnotherStringRepresentation() { let queens = try! Queens(white: [4, 3], black: [3, 4]) let board = "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ B _ _ _\n" + - "_ _ _ W _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _\n" + - "_ _ _ _ _ _ _ _" + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ B _ _ _\n" + + "_ _ _ W _ _ _ _\n" + + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ _ _ _ _\n" + + "_ _ _ _ _ _ _ _" XCTAssertEqual(board, queens.description) } - + func testCannotAttack() { let queens = try! Queens(white: [2, 3], black: [4, 7]) XCTAssertFalse(queens.canAttack) } - + func testCanAttackOnSameRow() { let queens = try! Queens(white: [2, 4], black: [2, 7]) XCTAssertTrue(queens.canAttack) } - + func testCanAttackOnSameColumn() { let queens = try! Queens(white: [5, 4], black: [2, 4]) XCTAssertTrue(queens.canAttack) } - + func testCanAttackOnDiagonal() { let queens = try! Queens(white: [1, 1], black: [6, 6]) XCTAssertTrue(queens.canAttack) } - + func testCanAttackOnOtherDiagonal() { let queens = try! Queens(white: [0, 6], black: [1, 7]) XCTAssertTrue(queens.canAttack) } - + func testCanAttackOnYetAnotherDiagonal() { let queens = try! Queens(white: [4, 1], black: [6, 3]) XCTAssertTrue(queens.canAttack) } - + func testCanAttackOnADiagonalSlantedTheOtherWay() { let queens = try! Queens(white: [6, 1], black: [1, 6]) XCTAssertTrue(queens.canAttack) } -} \ No newline at end of file +} diff --git a/exercises/raindrops/RaindropsExample.swift b/exercises/raindrops/RaindropsExample.swift index 9db9d0782..cec2c985a 100644 --- a/exercises/raindrops/RaindropsExample.swift +++ b/exercises/raindrops/RaindropsExample.swift @@ -1,29 +1,24 @@ -// Foundation not needed - +struct Raindrops { + private var drops: Int + var sounds: String = "" -struct Raindrops { - - private var drops:Int - var sounds:String = "" - - private func convert(number:Int)->String{ - let result = (number % 3, number % 5 , number % 7) - switch result{ - case (0,0,0):return "PlingPlangPlong" - case (_,0,0):return "PlangPlong" - case (0,_,0):return "PlingPlong" - case (0,0,_):return "PlingPlang" - case (_,_,0):return "Plong" - case (_,0,_):return "Plang" - case (0,_,_):return "Pling" + private func convert(_ number: Int) -> String { + let result = (number % 3, number % 5, number % 7) + switch result { + case (0, 0, 0):return "PlingPlangPlong" + case (_, 0, 0):return "PlangPlong" + case (0, _, 0):return "PlingPlong" + case (0, 0, _):return "PlingPlang" + case (_, _, 0):return "Plong" + case (_, 0, _):return "Plang" + case (0, _, _):return "Pling" default:return "\(number)" } } - - init(_ value:Int){ + + init(_ value: Int) { self.drops = value self.sounds = convert(value) } } - diff --git a/exercises/raindrops/RaindropsTest.swift b/exercises/raindrops/RaindropsTest.swift index c2132543e..821a7710a 100644 --- a/exercises/raindrops/RaindropsTest.swift +++ b/exercises/raindrops/RaindropsTest.swift @@ -1,73 +1,71 @@ -import XCTest - - - +#if swift(>=3.0) + import XCTest +#endif class RaindropsTest: XCTestCase { - + func test1() { XCTAssertEqual("1", Raindrops(1).sounds) } - + func test3() { XCTAssertEqual("Pling", Raindrops(3).sounds) } - + func test5() { XCTAssertEqual("Plang", Raindrops(5).sounds) } - + func test7() { XCTAssertEqual("Plong", Raindrops(7).sounds) } - + func test6() { XCTAssertEqual("Pling", Raindrops(6).sounds) } - + func test9() { XCTAssertEqual("Pling", Raindrops(9).sounds) } - + func test10() { XCTAssertEqual("Plang", Raindrops(10).sounds) } - + func test14() { XCTAssertEqual("Plong", Raindrops(14).sounds) } - + func test15() { XCTAssertEqual("PlingPlang", Raindrops(15).sounds) } - + func test21() { XCTAssertEqual("PlingPlong", Raindrops(21).sounds) } - + func test25() { XCTAssertEqual("Plang", Raindrops(25).sounds) } - + func test35() { XCTAssertEqual("PlangPlong", Raindrops(35).sounds) } - + func test49() { XCTAssertEqual("Plong", Raindrops(49).sounds) } - + func test52() { XCTAssertEqual("52", Raindrops(52).sounds) } - + func test105() { XCTAssertEqual("PlingPlangPlong", Raindrops(105).sounds) } - + func test12121() { XCTAssertEqual("12121", Raindrops(12_121).sounds) } - -} +} diff --git a/exercises/rna-transcription/RnaTranscriptionExample.swift b/exercises/rna-transcription/RnaTranscriptionExample.swift index 2fc845c0b..cb182ccaa 100644 --- a/exercises/rna-transcription/RnaTranscriptionExample.swift +++ b/exercises/rna-transcription/RnaTranscriptionExample.swift @@ -1,20 +1,18 @@ -// Foundation not needed - struct Nucleotide { - - var complementOfDNA:String{ return transcribe(dnaToRna) } - - private let value:String - - init(_ nucleotide:String){ + + var complementOfDNA: String { return transcribe(dnaToRna) } + + private let value: String + + init(_ nucleotide: String) { self.value = nucleotide } - - private let dnaToRna:[Character:String] = [ "G": "C" , "C": "G" , "T": "A" , "A": "U" ] - private func transcribe(dict:[Character : String]) -> String{ + private let dnaToRna: [Character:String] = [ "G": "C", "C": "G", "T": "A", "A": "U" ] + + private func transcribe(_ dict: [Character : String]) -> String { var tempText = "" - for each in self.value.characters{ + for each in self.value.characters { tempText += dict[each] ?? "" } return tempText diff --git a/exercises/rna-transcription/RnaTranscriptionTest.swift b/exercises/rna-transcription/RnaTranscriptionTest.swift index 46bae0f29..66caacec4 100644 --- a/exercises/rna-transcription/RnaTranscriptionTest.swift +++ b/exercises/rna-transcription/RnaTranscriptionTest.swift @@ -1,26 +1,27 @@ - -import XCTest +#if swift(>=3.0) + import XCTest +#endif class RnaTranscriptionTest: XCTestCase { - + func testRnaComplementOfCytosineIsGuanine() { XCTAssertEqual("G", Nucleotide("C").complementOfDNA) } - + func testRnaComplementOfGuanineIsCytosine() { XCTAssertEqual("C", Nucleotide("G").complementOfDNA) } - + func testRnaComplementOfThymineIsAdenine() { XCTAssertEqual("A", Nucleotide("T").complementOfDNA) } - + func testRnaComplementOfAdenineIsUracil() { XCTAssertEqual("U", Nucleotide("A").complementOfDNA) } - + func testRnaComplement() { XCTAssertEqual("UGCACCAGAAUU", Nucleotide("ACGTGGTCTTAA").complementOfDNA) } - + } diff --git a/exercises/robot-name/RobotNameExample.swift b/exercises/robot-name/RobotNameExample.swift index 3c321f650..cadcdc3d5 100644 --- a/exercises/robot-name/RobotNameExample.swift +++ b/exercises/robot-name/RobotNameExample.swift @@ -1,22 +1,20 @@ import Darwin - - struct Robot { var name: String - + init() { - let numberPart = (Int(rand()) % 899) + 100 + let numberPart = (Int(arc4random()) % 899) + 100 name = generateRandomLetter() + generateRandomLetter() + "\(numberPart)" } mutating func resetName() { - let numberPart = (Int(rand()) % 899) + 100 + let numberPart = (Int(arc4random()) % 899) + 100 name = generateRandomLetter() + generateRandomLetter() + "\(numberPart)" } } -private func convertStringToStringArray(input: String) -> [String] { +private func convertStringToStringArray(_ input: String) -> [String] { var characterArray: [String] = [] for character in input.characters { characterArray.append("\(character)") @@ -27,6 +25,6 @@ private func convertStringToStringArray(input: String) -> [String] { private func generateRandomLetter() -> String { let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" let letters = convertStringToStringArray(alphabet) - let randomIndex = Int(rand()) % letters.count + let randomIndex = Int(arc4random()) % letters.count return letters[randomIndex] } diff --git a/exercises/robot-name/RobotNameTest.swift b/exercises/robot-name/RobotNameTest.swift index b61afb6a2..840a3ddfa 100644 --- a/exercises/robot-name/RobotNameTest.swift +++ b/exercises/robot-name/RobotNameTest.swift @@ -1,12 +1,12 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class RobotNameTest: XCTestCase { - func robotNameIsCorrectlyFormatted(name: String) -> Bool { - let robotNameRegex = try? NSRegularExpression(pattern: "\\A\\w{2}\\d{3}\\z", options: NSRegularExpressionOptions.CaseInsensitive) - guard let matches = robotNameRegex?.matchesInString(name, options: .WithoutAnchoringBounds, range: NSMakeRange(0, name.characters.count)) else { return false } + func robotNameIsCorrectlyFormatted(_ name: String) -> Bool { + let robotNameRegex = try? RegularExpression(pattern: "\\A\\w{2}\\d{3}\\z", options: RegularExpression.Options.caseInsensitive) + guard let matches = robotNameRegex?.matches(in: name, options: .withoutAnchoringBounds, range: NSMakeRange(0, name.characters.count)) else { return false } return matches.count > 0 } diff --git a/exercises/robot-simulator/RobotSimulatorExample.swift b/exercises/robot-simulator/RobotSimulatorExample.swift index ea96e727d..01ccee6f2 100644 --- a/exercises/robot-simulator/RobotSimulatorExample.swift +++ b/exercises/robot-simulator/RobotSimulatorExample.swift @@ -1,37 +1,33 @@ -// Foundation not needed - - - struct SimulatedRobot { - + enum Direction { - case North - case East - case South - case West - - static let allValues: [Direction] = [.North, .East, .South, .West] + case north + case east + case south + case west + + static let allValues: [Direction] = [.north, .east, .south, .west] } - + enum Instruction: String { case TurnLeft = "L" case TurnRight = "R" case Advance = "A" } - - var bearing: Direction = .North + + var bearing: Direction = .north var x: Int = 0 var y: Int = 0 var coordinates: [Int] { return [x, y] } - - mutating func orient(bearing: Direction) { + + mutating func orient(_ bearing: Direction) { self.bearing = bearing } - + mutating func turnRight() { - if let index = Direction.allValues.indexOf(bearing) { + if let index = Direction.allValues.index(of: bearing) { var newIndex = index + 1 if newIndex > 3 { newIndex -= 4 @@ -39,9 +35,9 @@ struct SimulatedRobot { bearing = Direction.allValues[newIndex] } } - + mutating func turnLeft() { - if let index = Direction.allValues.indexOf(bearing) { + if let index = Direction.allValues.index(of: bearing) { var newIndex = index - 1 if newIndex < 0 { newIndex += 4 @@ -49,51 +45,48 @@ struct SimulatedRobot { bearing = Direction.allValues[newIndex] } } - - mutating func at(x x: Int, y: Int) { + + mutating func at(x: Int, y: Int) { self.x = x self.y = y } - + mutating func advance() { switch bearing { - // Note: ++ and -- will be deprecated in Swift 2.2 and removed in Swift 3.0 - // See https://github.com/apple/swift-evolution/blob/master/proposals/0004-remove-pre-post-inc-decrement.md - case .North: y += 1 - case .East: x += 1 - case .South: y -= 1 - case .West: x -= 1 + case .north: y += 1 + case .east: x += 1 + case .south: y -= 1 + case .west: x -= 1 } } - - func instructions(instructions: String) -> [Instruction] { + + func instructions(_ instructions: String) -> [Instruction] { var result = [Instruction]() - + let characters = instructions.characters.map { String($0) } - + for character in characters { if let instruction = Instruction(rawValue: character) { result.append(instruction) } } - + return result } - - mutating func place(x x: Int, y: Int, direction: Direction) { + + mutating func place(x: Int, y: Int, direction: Direction) { at(x: x, y: y) orient(direction) } - - mutating func evaluate(commands: String) { + + mutating func evaluate(_ commands: String) { for instruction in instructions(commands) { switch instruction { - case .TurnLeft: turnLeft() - case .TurnRight: turnRight() - case .Advance: advance() + case .TurnLeft: turnLeft() + case .TurnRight: turnRight() + case .Advance: advance() } } } } - diff --git a/exercises/robot-simulator/RobotSimulatorTest.swift b/exercises/robot-simulator/RobotSimulatorTest.swift index cc4e81331..e2afdb68f 100644 --- a/exercises/robot-simulator/RobotSimulatorTest.swift +++ b/exercises/robot-simulator/RobotSimulatorTest.swift @@ -1,161 +1,161 @@ -import XCTest +#if swift(>=3.0) + import XCTest +#endif +class RobotSimulatorTest: XCTestCase { + var robot = SimulatedRobot() -class RobotSimulatorTest: XCTestCase { - - var robot = SimulatedRobot() - func testRobotBearingEast() { - robot.orient(.East) - XCTAssertEqual([.East], [robot.bearing]) + robot.orient(.east) + XCTAssertEqual([.east], [robot.bearing]) } - + func testRobotBearingWest() { - robot.orient(.West) - XCTAssertEqual([.West], [robot.bearing]) + robot.orient(.west) + XCTAssertEqual([.west], [robot.bearing]) } func testRobotBearingNorth() { - robot.orient(.North) - XCTAssertEqual([.North], [robot.bearing]) + robot.orient(.north) + XCTAssertEqual([.north], [robot.bearing]) } - + func testRobotBearingSouth() { - robot.orient(.South) - XCTAssertEqual([.South], [robot.bearing]) + robot.orient(.south) + XCTAssertEqual([.south], [robot.bearing]) } - + func testTurnRightFromNorth() { - robot.orient(.North) + robot.orient(.north) robot.turnRight() - XCTAssertEqual([.East], [robot.bearing]) + XCTAssertEqual([.east], [robot.bearing]) } - + func testTurnRightFromEast() { - robot.orient(.East) + robot.orient(.east) robot.turnRight() - XCTAssertEqual([.South], [robot.bearing]) + XCTAssertEqual([.south], [robot.bearing]) } - + func testTurnRightFromSouth() { - robot.orient(.South) + robot.orient(.south) robot.turnRight() - XCTAssertEqual([.West], [robot.bearing]) + XCTAssertEqual([.west], [robot.bearing]) } - + func testTurnRightFromWest() { - robot.orient(.West) + robot.orient(.west) robot.turnRight() - XCTAssertEqual([.North], [robot.bearing]) + XCTAssertEqual([.north], [robot.bearing]) } - + func testTurnLeftFromNorth() { - robot.orient(.North) + robot.orient(.north) robot.turnLeft() - XCTAssertEqual([.West], [robot.bearing]) + XCTAssertEqual([.west], [robot.bearing]) } - + func testTurnLeftFromEast() { - robot.orient(.East) + robot.orient(.east) robot.turnLeft() - XCTAssertEqual([.North], [robot.bearing]) + XCTAssertEqual([.north], [robot.bearing]) } - + func testTurnLeftFromSouth() { - robot.orient(.South) + robot.orient(.south) robot.turnLeft() - XCTAssertEqual([.East], [robot.bearing]) + XCTAssertEqual([.east], [robot.bearing]) } - + func testTurnLeftFromWest() { - robot.orient(.West) + robot.orient(.west) robot.turnLeft() - XCTAssertEqual([.South], [robot.bearing]) + XCTAssertEqual([.south], [robot.bearing]) } func testRobotCoordinates() { robot.at(x: 3, y: 0) XCTAssertEqual([3, 0], robot.coordinates) } - + func testOtherRobotCoordinates() { robot.at(x: -2, y: 5) XCTAssertEqual([-2, 5], robot.coordinates) } - + func testAdvanceWhenFacingNorth() { robot.at(x: 0, y: 0) - robot.orient(.North) + robot.orient(.north) robot.advance() XCTAssertEqual([0, 1], robot.coordinates) } - + func testAdvanceWhenFacingEast() { robot.at(x: 0, y: 0) - robot.orient(.East) + robot.orient(.east) robot.advance() XCTAssertEqual([1, 0], robot.coordinates) } - + func testAdvanceWhenFacingSouth() { robot.at(x: 0, y: 0) - robot.orient(.South) + robot.orient(.south) robot.advance() XCTAssertEqual([0, -1], robot.coordinates) } - + func testAdvanceWhenFacingWest() { robot.at(x: 0, y: 0) - robot.orient(.West) + robot.orient(.west) robot.advance() XCTAssertEqual([-1, 0], robot.coordinates) } - + func testInstructionForTurningLeft() { XCTAssertEqual([.TurnLeft], robot.instructions("L")) } - + func testInstructionForTurningRight() { XCTAssertEqual([.TurnRight], robot.instructions("R")) } - + func testInstructionForAdvancing() { XCTAssertEqual([.Advance], robot.instructions("A")) } - + func testSeriesOfInstructions() { XCTAssertEqual([.TurnRight, .Advance, .Advance, .TurnLeft], robot.instructions("RAAL")) } - + func testInstructRobot() { var robot = SimulatedRobot() - robot.place(x: -2, y: 1, direction: .East) + robot.place(x: -2, y: 1, direction: .east) robot.evaluate("RLAALAL") - + XCTAssertEqual([0, 2], robot.coordinates) - XCTAssertEqual([.West], [robot.bearing]) + XCTAssertEqual([.west], [robot.bearing]) } - + func testInstructManyRobots() { var robot1 = SimulatedRobot() var robot2 = SimulatedRobot() var robot3 = SimulatedRobot() - robot1.place(x: 0, y: 0, direction: .North) - robot2.place(x: 2, y: -7, direction: .East) - robot3.place(x: 8, y: 4, direction: .South) + robot1.place(x: 0, y: 0, direction: .north) + robot2.place(x: 2, y: -7, direction: .east) + robot3.place(x: 8, y: 4, direction: .south) robot1.evaluate("LAAARALA") robot2.evaluate("RRAAAAALA") robot3.evaluate("LAAARRRALLLL") - + XCTAssertEqual([-4, 1], robot1.coordinates) - XCTAssertEqual([.West], [robot1.bearing]) - + XCTAssertEqual([.west], [robot1.bearing]) + XCTAssertEqual([-3, -8], robot2.coordinates) - XCTAssertEqual([.South], [robot2.bearing]) - + XCTAssertEqual([.south], [robot2.bearing]) + XCTAssertEqual([11, 5], robot3.coordinates) - XCTAssertEqual([.North], [robot3.bearing]) + XCTAssertEqual([.north], [robot3.bearing]) } - + } diff --git a/exercises/roman-numerals/RomanNumeralsExample.swift b/exercises/roman-numerals/RomanNumeralsExample.swift index 602423a1c..915cba75c 100644 --- a/exercises/roman-numerals/RomanNumeralsExample.swift +++ b/exercises/roman-numerals/RomanNumeralsExample.swift @@ -1,36 +1,29 @@ -// Foundation not needed +extension String { - - -extension String{ - - init(_ value:RomanNumeral){ + init(_ value: RomanNumeral) { self = value.romanNumeral - } + } } -struct RomanNumeral{ - - var romanNumeral:String = "" - - private func toRomanNumerals(input:Int) ->String{ +struct RomanNumeral { + + var romanNumeral: String = "" + + private func toRomanNumerals(_ input: Int) -> String { var arabicToRoman = [1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"] var i = input var s = "" - for arabic in arabicToRoman.keys.sort(> ){ - while i >= arabic{ + for arabic in arabicToRoman.keys.sorted(isOrderedBefore: > ) { + while i >= arabic { s += arabicToRoman[arabic] ?? "" i -= arabic } } return s } - - init(_ value:Int){ - + + init(_ value: Int) { + self.romanNumeral = toRomanNumerals(value) } - - } - diff --git a/exercises/roman-numerals/RomanNumeralsTest.swift b/exercises/roman-numerals/RomanNumeralsTest.swift index 61f7bf5f7..35b2689e6 100644 --- a/exercises/roman-numerals/RomanNumeralsTest.swift +++ b/exercises/roman-numerals/RomanNumeralsTest.swift @@ -1,79 +1,79 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class RomanNumeralsTest: XCTestCase { - + func test1() { XCTAssertEqual("I", String(RomanNumeral(1))) } - + func test2() { XCTAssertEqual("II", String(RomanNumeral(2))) } - + func test3() { XCTAssertEqual("III", String(RomanNumeral(3))) } - + func test4() { XCTAssertEqual("IV", String(RomanNumeral(4))) } - + func test5() { XCTAssertEqual("V", String(RomanNumeral(5))) } - + func test6() { XCTAssertEqual("VI", String(RomanNumeral(6))) } - + func test9() { XCTAssertEqual("IX", String(RomanNumeral(9))) } - + func test27() { XCTAssertEqual("XXVII", String(RomanNumeral(27))) } - + func test48() { XCTAssertEqual("XLVIII", String(RomanNumeral(48))) } - + func test59() { XCTAssertEqual("LIX", String(RomanNumeral(59))) } - + func test93() { XCTAssertEqual("XCIII", String(RomanNumeral(93))) } - + func test141() { XCTAssertEqual("CXLI", String(RomanNumeral(141))) } - + func test163() { XCTAssertEqual("CLXIII", String(RomanNumeral(163))) } - + func test402() { XCTAssertEqual("CDII", String(RomanNumeral(402))) } - + func test575() { XCTAssertEqual("DLXXV", String(RomanNumeral(575))) } - + func test911() { XCTAssertEqual("CMXI", String(RomanNumeral(911))) } - + func test1024() { XCTAssertEqual("MXXIV", String(RomanNumeral(1024))) } - + func test3000() { XCTAssertEqual("MMM", String(RomanNumeral(3000))) } - + } diff --git a/exercises/saddle-points/SaddlePointsExample.swift b/exercises/saddle-points/SaddlePointsExample.swift index b4f833ef0..907217d55 100644 --- a/exercises/saddle-points/SaddlePointsExample.swift +++ b/exercises/saddle-points/SaddlePointsExample.swift @@ -1,51 +1,47 @@ -// Foundation not needed - - - struct SaddlePointsMatrix { - + let rows: [[Int]] let columns: [[Int]] let saddlePoints: [[Int]] - + init(_ matrix: String) { var rows = [[Int]]() - - let rowItems = matrix.characters.split("\n").map { String($0) } - + + let rowItems = matrix.characters.split(separator: "\n").map { String($0) } + for row in rowItems { - let rowItems = row.characters.split(" ").map { Int(String($0)) ?? 0 } + let rowItems = row.characters.split(separator: " ").map { Int(String($0)) ?? 0 } rows.append(rowItems) } - + self.rows = rows - + var columns = [[Int]]() - + let count = rows[0].count for i in 0..=3.0) + import XCTest +#endif class SaddlePointsTest: XCTestCase { - + func testExtractARow() { let matrix = SaddlePointsMatrix("1 2\n10 20") XCTAssertEqual([1, 2], matrix.rows[0]) } - + func testExtractSameRowAgain() { let matrix = SaddlePointsMatrix("9 7\n8 6") XCTAssertEqual([9, 7], matrix.rows[0]) } - + func testExtractOtherRow() { let matrix = SaddlePointsMatrix("9 8 7\n19 18 17") XCTAssertEqual([19, 18, 17], matrix.rows[1]) } - + func testExtractOtherRowAgain() { let matrix = SaddlePointsMatrix("1 4 9\n16 25 36") XCTAssertEqual([16, 25, 36], matrix.rows[1]) } - + func testExtractAColumn() { let matrix = SaddlePointsMatrix("1 2 3\n4 5 6\n7 8 9\n 8 7 6") XCTAssertEqual([1, 4, 7, 8], matrix.columns[0]) } - + func testExtractAnotherColumn() { let matrix = SaddlePointsMatrix("89 1903 3\n18 3 1\n9 4 800") XCTAssertEqual([1903, 3, 4], matrix.columns[1]) } - + func testNoSaddlePoint() { let matrix = SaddlePointsMatrix("2 1\n1 2") XCTAssertEqual([], matrix.saddlePoints) } - + func testASaddlePoint() { let matrix = SaddlePointsMatrix("1 2\n3 4") XCTAssertEqual([[0, 1]], matrix.saddlePoints) } - + func testAnotherSaddlePoint() { let matrix = SaddlePointsMatrix("18 3 39 19 91\n38 10 8 77 320\n3 4 8 6 7") XCTAssertEqual([[2, 2]], matrix.saddlePoints) } - + func testMultipleSaddlePoints() { let matrix = SaddlePointsMatrix("4 5 4\n3 5 5\n1 5 4") XCTAssertEqual([[0, 1], [1, 1], [2, 1]], matrix.saddlePoints) } - + } diff --git a/exercises/scrabble-score/ScrabbleScoreExample.swift b/exercises/scrabble-score/ScrabbleScoreExample.swift index 8082345e7..d2a808476 100644 --- a/exercises/scrabble-score/ScrabbleScoreExample.swift +++ b/exercises/scrabble-score/ScrabbleScoreExample.swift @@ -1,68 +1,54 @@ -// Foundation not needed - +private extension String { + func containsCustom(_ input: Character) -> Bool { + return contains(String(input)) -private extension String { - - func containsCustom(input: Character) ->Bool{ - #if swift(>=3.0) - return contains(String(input)) - #else - return containsString(String(input)) - #endif } - - func lowercasedCustom()->String{ - #if swift(>=3.0) - return lowercased() - #else - return lowercaseString - #endif + + func lowercasedCustom() -> String { + return lowercased() + } - - private func stripCharacters(charsToRemove:String) -> String{ + + private func stripCharacters(_ charsToRemove: String) -> String { var returnString = "" - self.characters.forEach{ - if !charsToRemove.containsCustom($0){ + self.characters.forEach { + if !charsToRemove.containsCustom($0) { returnString.append($0) }} return returnString } - var stripWhiteSpace:String { + var stripWhiteSpace: String { return stripCharacters(" ") - } - - var IsEmptyOrWhiteSpace:Bool { get { + } + + var isEmptyOrWhiteSpace: Bool { get { return self.stripWhiteSpace.isEmpty }}} +struct Scrabble { - -struct Scrabble{ - static var letterScores = - [ "a": 1 , "e": 1 , "i": 1 , "o": 1 , "u": 1 , "l": 1 , "n": 1 , "r": 1 , "s": 1 , "t": 1 , "d": 2 , "g": 2 , "b": 3 , "c": 3 , "m": 3 , "p": 3 , "f": 4 , "h": 4 , "v": 4 , "w": 4 , "y": 4 , "k": 5 , "j": 8 , "x": 8 , "q": 10 , "z": 10 ] - - - - static func score(input:String) -> Int { - if (input.IsEmptyOrWhiteSpace ){ + [ "a": 1, "e": 1, "i": 1, "o": 1, "u": 1, "l": 1, "n": 1, "r": 1, "s": 1, "t": 1, "d": 2, "g": 2, "b": 3, "c": 3, "m": 3, "p": 3, "f": 4, "h": 4, "v": 4, "w": 4, "y": 4, "k": 5, "j": 8, "x": 8, "q": 10, "z": 10 ] + + static func score(_ input: String) -> Int { + if input.isEmptyOrWhiteSpace { return 0} - - var count:Int = 0 - for each in input.lowercasedCustom().characters{ + + var count: Int = 0 + for each in input.lowercasedCustom().characters { count += letterScores[String(each)] ?? 0 } return count } - - var word:String = "" - - var score:Int = 0 - - init(_ word:String?) { + + var word: String = "" + + var score: Int = 0 + + init(_ word: String?) { self.word = word ?? "" self.score = Scrabble.score(word ?? "") - + } -} \ No newline at end of file +} diff --git a/exercises/scrabble-score/ScrabbleScoreTest.swift b/exercises/scrabble-score/ScrabbleScoreTest.swift index cd9e9a6a1..b73dbdf33 100644 --- a/exercises/scrabble-score/ScrabbleScoreTest.swift +++ b/exercises/scrabble-score/ScrabbleScoreTest.swift @@ -1,43 +1,43 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class ScrabbleScoreTest: XCTestCase { - + func testEmptyWordScoresZero() { XCTAssertEqual( 0, Scrabble("").score) } - + func testWhitespaceScoresZero() { XCTAssertEqual( 0, Scrabble(" \t\n").score) } - + func testNilScoresZero() { XCTAssertEqual( 0, Scrabble(nil).score) } - + func testScoresVeryShortWord() { XCTAssertEqual( 1, Scrabble("a").score) } - + func testScoresOtherVeryShortWord() { XCTAssertEqual( 4, Scrabble("f").score) } - + func testSimpleWordScoresTheNumberOfLetters() { XCTAssertEqual( 6, Scrabble("street").score) } - + func testComplicatedWordScoresMore() { XCTAssertEqual( 22, Scrabble("quirky").score) } - + func testScoresAreCaseInsensitive() { XCTAssertEqual( 41, Scrabble("OXYPHENBUTAZONE").score) } - + func testConvenientScoring() { XCTAssertEqual( 13, Scrabble.score("alacrity")) } - + } diff --git a/exercises/secret-handshake/SecretHandshakeExample.swift b/exercises/secret-handshake/SecretHandshakeExample.swift index e6dcb0361..cecd23d4c 100644 --- a/exercises/secret-handshake/SecretHandshakeExample.swift +++ b/exercises/secret-handshake/SecretHandshakeExample.swift @@ -1,33 +1,28 @@ -// Foundation not needed +struct SecretHandshake { + var commandValue: Int + var commandValues = [1: "wink", 2: "double blink", 4: "close your eyes", 8: "jump"] - -struct SecretHandshake{ - - var commandValue:Int - var commandValues = [1: "wink" , 2: "double blink", 4: "close your eyes" , 8: "jump"] - - init(_ commandValue:Int){ + init(_ commandValue: Int) { self.commandValue = commandValue } - - var shouldReverse:Bool {return (commandValue & 16) != 0} - - var commands:[String] {return commandsFunc()} - - private func commandsFunc()->[String] { + + var shouldReverse: Bool {return (commandValue & 16) != 0} + + var commands: [String] {return commandsFunc()} + + private func commandsFunc() -> [String] { var commands = [String]() - for key in Array(commandValues.keys).sort( < ){ + for key in Array(commandValues.keys).sorted( isOrderedBefore: < ) { if (commandValue & key) != 0 { commands.append(commandValues[key]!) } } - - if shouldReverse{ - return Array(commands.reverse()) - } - else { + + if shouldReverse { + return Array(commands.reversed()) + } else { return commands } } -} \ No newline at end of file +} diff --git a/exercises/secret-handshake/SecretHandshakeTest.swift b/exercises/secret-handshake/SecretHandshakeTest.swift index 1ebd1fe37..0de597c24 100644 --- a/exercises/secret-handshake/SecretHandshakeTest.swift +++ b/exercises/secret-handshake/SecretHandshakeTest.swift @@ -1,49 +1,48 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class SecretHandshakeTest: XCTestCase { - + func testHandshake1ToWink() { let handshake = SecretHandshake(1) XCTAssertEqual(["wink"], handshake.commands) } - + func testHandshake10ToDoubleBlink() { let handshake = SecretHandshake(2) XCTAssertEqual(["double blink"], handshake.commands) } - + func testHandshake100ToCloseYourEyes() { let handshake = SecretHandshake(4) XCTAssertEqual(["close your eyes"], handshake.commands) } - + func testHandshake1000ToJump() { let handshake = SecretHandshake(8) XCTAssertEqual(["jump"], handshake.commands) } - + func testHandshake11ToWinkAndDoubleBlink() { let handshake = SecretHandshake(3) XCTAssertEqual(["wink", "double blink"], handshake.commands) } - + func testHandshake10011ToDoubleBlinkAndWink() { let handshake = SecretHandshake(19) XCTAssertEqual(["double blink", "wink"], handshake.commands) } - + func testHandshake11111ToDoubleBlinkAndWink() { let handshake = SecretHandshake(31) let expected = ["jump", "close your eyes", "double blink", "wink"] XCTAssertEqual(expected, handshake.commands) } - + func testNonValidHandshake() { let handshake = SecretHandshake(0) XCTAssertEqual([], handshake.commands) } - -} \ No newline at end of file + +} diff --git a/exercises/series/SeriesExample.swift b/exercises/series/SeriesExample.swift index 37b9f2b06..a421445f4 100644 --- a/exercises/series/SeriesExample.swift +++ b/exercises/series/SeriesExample.swift @@ -1,27 +1,20 @@ -// Foundation not needed - - - struct Series { - + var numberString = "" - - init(_ numString:String){ + + init(_ numString: String) { self.numberString = numString } - - func slices(chunkSize:Int)->[[Int]]{ - var numberStringArray = Array(numberString.characters).map{Int("\($0)") ?? 0} + + func slices(_ chunkSize: Int) -> [[Int]] { + var numberStringArray = Array(numberString.characters).map {Int("\($0)") ?? 0} let count = numberStringArray.count var start = 0 var end = chunkSize var tempArrayReturn = [[Int]]() - - #if swift(>=3.0) + let enumarated = (0..<(count)).enumerated() - #else - let enumarated = (0..<(count)).enumerate() - #endif + for (_, _) in enumarated { if end < count+1 { let tempArray = Array(numberStringArray[start ..< end]) @@ -32,6 +25,4 @@ struct Series { } return tempArrayReturn } - - -} \ No newline at end of file +} diff --git a/exercises/series/SeriesTest.swift b/exercises/series/SeriesTest.swift index 203525e41..c087828f7 100644 --- a/exercises/series/SeriesTest.swift +++ b/exercises/series/SeriesTest.swift @@ -1,81 +1,80 @@ -import XCTest - - - +#if swift(>=3.0) + import XCTest +#endif class SeriesTest: XCTestCase { - + func testSimpleSlicesOfOne() { let series = Series("01234") XCTAssertEqual([[0], [1], [2], [3], [4]], series.slices(1)) } - + func testSimpleSlicesOfOneAgain() { let series = Series("92834") XCTAssertEqual([[9], [2], [8], [3], [4]], series.slices(1)) } - + func testSimpleSlicesOfTwo() { let series = Series("01234") XCTAssertEqual([[0, 1], [1, 2], [2, 3], [3, 4]], series.slices(2)) } - + func testOtherSlicesOfTwo() { let series = Series("98273463") let expected = [[9, 8], [8, 2], [2, 7], [7, 3], [3, 4], [4, 6], [6, 3]] XCTAssertEqual(expected, series.slices(2)) } - + func testSimpleSlicesOfTwoAgain() { let series = Series("37103") XCTAssertEqual([[3, 7], [7, 1], [1, 0], [0, 3]], series.slices(2)) } - + func testSimpleSlicesOfThree() { let series = Series("01234") XCTAssertEqual([[0, 1, 2], [1, 2, 3], [2, 3, 4]], series.slices(3)) } - + func testSimpleSlicesOfThreeAgain() { let series = Series("31001") XCTAssertEqual([[3, 1, 0], [1, 0, 0], [0, 0, 1]], series.slices(3)) } - + func testOtherSlicesOfThree() { let series = Series("982347") let expected = [[9, 8, 2], [8, 2, 3], [2, 3, 4], [3, 4, 7]] XCTAssertEqual(expected, series.slices(3)) } - + func testSimpleSlicesOfFour() { let series = Series("01234") XCTAssertEqual([[0, 1, 2, 3], [1, 2, 3, 4]], series.slices(4)) } - + func testSimpleSlicesOfFourAgain() { let series = Series("91274") XCTAssertEqual([[9, 1, 2, 7], [1, 2, 7, 4]], series.slices(4)) } - + func testSimpleSlicesOfFive() { let series = Series("01234") XCTAssertEqual([[0, 1, 2, 3, 4]], series.slices(5)) } - + func testSimpleSlicesOfFiveAgain() { let series = Series("81228") XCTAssertEqual([[8, 1, 2, 2, 8]], series.slices(5)) } - + func testSimpleSliceThatBlowsUp() { let series = Series("01234") - XCTAssertEqual([],series.slices(6)) + XCTAssertEqual([], series.slices(6)) } - + func testMoreComplicatedSliceThatBlowsUp() { let sliceString = "01032987583" let series = Series(sliceString) XCTAssertEqual([], series.slices(12)) } - -} \ No newline at end of file + +} diff --git a/exercises/sieve/SieveExample.swift b/exercises/sieve/SieveExample.swift index 585fda614..766fedd66 100644 --- a/exercises/sieve/SieveExample.swift +++ b/exercises/sieve/SieveExample.swift @@ -1,31 +1,26 @@ -// Foundation not needed - - - struct Sieve { - var value:Int = 0 - init(_ num:Int){ + var value: Int = 0 + init(_ num: Int) { self.value = num } - - var primes:[Int]{return primesFunc(self.value ) } - - func primesFunc(limit:Int) -> [Int]{ - - if limit < 2 { return []} - else{ - let tempArray = Array(2...limit) - return tempArray.filter{Sieve.onlyDivisorSelf($0)} + + var primes: [Int] {return primesFunc(self.value ) } + + func primesFunc(_ limit: Int) -> [Int] { + + if limit < 2 { return []} else { + let tempArray = Array(2...limit) + return tempArray.filter {Sieve.onlyDivisorSelf($0)} } } - - static func onlyDivisorSelf( number:Int)->Bool{ + + static func onlyDivisorSelf( _ number: Int) -> Bool { var number = number - + var primes = [Int]() - var divisor:Int = 2 - while (number > 1){ - while (number % divisor == 0){ + var divisor: Int = 2 + while (number > 1) { + while (number % divisor == 0) { primes.append(divisor) number /= divisor } @@ -33,13 +28,6 @@ struct Sieve { } if primes.count == 1 {return true} else {return false} } - - - - - - - -} \ No newline at end of file +} diff --git a/exercises/sieve/SieveTest.swift b/exercises/sieve/SieveTest.swift index 5b1584678..1b3a92f0d 100644 --- a/exercises/sieve/SieveTest.swift +++ b/exercises/sieve/SieveTest.swift @@ -1,15 +1,14 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class SieveTest: XCTestCase { - + func testAFewPrimes() { let expected = [2, 3, 5, 7] XCTAssertEqual(expected, Sieve(10).primes) } - + func testPrimes() { let expected = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, @@ -29,5 +28,5 @@ class SieveTest: XCTestCase { ] XCTAssertEqual(expected, Sieve(1000).primes) } - + } diff --git a/exercises/simple-cipher/SimpleCipherExample.swift b/exercises/simple-cipher/SimpleCipherExample.swift index c97007afa..619b32cf1 100644 --- a/exercises/simple-cipher/SimpleCipherExample.swift +++ b/exercises/simple-cipher/SimpleCipherExample.swift @@ -1,40 +1,28 @@ import Darwin - - -func arc4random_uniform(input:Int)->Int{ +func arc4random_uniform(_ input: Int) -> Int { let temp = UInt32(input) return Int(arc4random_uniform(temp)) } - - -public struct Cipher -{ +public struct Cipher { private let abc = "abcdefghijklmnopqrstuvwxyz" - private var alphabet:[Character] { return Array(abc.characters) } - private(set) var key:String = "" - private var keyArray:[Character] { return Array(key.characters) } - - - private func randomKeySet()->String{ + private var alphabet: [Character] { return Array(abc.characters) } + private(set) var key: String = "" + private var keyArray: [Character] { return Array(key.characters) } + private func randomKeySet() -> String { var tempKey = "" - for _ in (0..<100).enumerate(){ + for _ in (0..<100).enumerated() { tempKey.append(alphabet[arc4random_uniform(alphabet.count)]) } return tempKey } - - - init(){ + init() { key = randomKeySet() } - - - init?(key:String) - { - if isLowerCaseAlfabet(key){ + init?(key: String) { + if isLowerCaseAlfabet(key) { self.key = key - + if key.isEmpty { return nil } @@ -42,69 +30,55 @@ public struct Cipher //self.key = randomKeySet() // Alternative non Optional faiulure } } - - - func isLowerCaseAlfabet(inkey:String)-> Bool{ + func isLowerCaseAlfabet(_ inkey: String) -> Bool { var valid = true - inkey.characters.forEach{ - - if "abcdefghijklmnopqrstuvwxyz".containsString(String($0)) == false { + inkey.characters.forEach { + + if "abcdefghijklmnopqrstuvwxyz".contains(String($0)) == false { valid = false } } return valid } - - - func encode(plaintext:String) ->String - { + func encode(_ plaintext: String) -> String { let plainTextArray = Array(plaintext.characters) - - func encodeCharacter(plaintext:String, idx:Int)->Character - { + + func encodeCharacter(_ plaintext: String, idx: Int) -> Character { //let plainTextArray = Array(plaintext) // hack for subscript support for Strings - var alphabetIdx:Int = - (alphabet.indexOf(plainTextArray[idx]) ?? 0) + - (alphabet.indexOf(keyArray[idx]) ?? 0) + var alphabetIdx: Int = + (alphabet.index(of: plainTextArray[idx]) ?? 0) + + (alphabet.index(of: keyArray[idx]) ?? 0) if alphabetIdx >= alphabet.count { alphabetIdx -= alphabet.count } return alphabet[alphabetIdx] } - + var ciphertext = "" for i in 0 ..< min(plainTextArray.count, keyArray.count) { ciphertext.append(encodeCharacter(plaintext, idx: i)) } return ciphertext } - - - - func decode(ciphertext:String)->String - { + + func decode(_ ciphertext: String) -> String { let cipherTextArray = Array(ciphertext.characters) - - func decodeCharacter(ciphertext:String, idx:Int)-> Character - { + + func decodeCharacter(_ ciphertext: String, idx: Int) -> Character { //let cipherTextArray = Array(ciphertext) // no native subscript for String - var alphabetIdx:Int = - (alphabet.indexOf(cipherTextArray[idx]) ?? 0) - - (alphabet.indexOf(keyArray[idx]) ?? 0) - if alphabetIdx < 0{ + var alphabetIdx: Int = + (alphabet.index(of: cipherTextArray[idx]) ?? 0) - + (alphabet.index(of: keyArray[idx]) ?? 0) + if alphabetIdx < 0 { alphabetIdx += alphabet.count } return alphabet[alphabetIdx] } - - var plaintext = "" - - for i in 0 ..< cipherTextArray.count { + + for i in 0 ..< cipherTextArray.count { plaintext.append(decodeCharacter(ciphertext, idx: i)) } return plaintext } - - -} \ No newline at end of file +} diff --git a/exercises/simple-cipher/SimpleCipherTest.swift b/exercises/simple-cipher/SimpleCipherTest.swift index 562c28290..757ea1b44 100644 --- a/exercises/simple-cipher/SimpleCipherTest.swift +++ b/exercises/simple-cipher/SimpleCipherTest.swift @@ -1,21 +1,20 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class SimpleCipherTest: XCTestCase { func testCipherEncode() { let cipher = Cipher() let plaintext = "aaaaaaaaaa" - let expected = cipher.key.substringToIndex(cipher.key.startIndex.advancedBy(10)) + let expected = cipher.key.substring(to: cipher.key.characters.index(cipher.key.startIndex, offsetBy: 10)) XCTAssertEqual(expected, cipher.encode(plaintext)) } func testCipherDecode() { let cipher = Cipher() let plaintext = "aaaaaaaaaa" - let expected = cipher.key.substringToIndex(cipher.key.startIndex.advancedBy(10)) + let expected = cipher.key.substring(to: cipher.key.characters.index(cipher.key.startIndex, offsetBy: 10)) XCTAssertEqual(plaintext, cipher.decode(expected)) } @@ -25,7 +24,7 @@ class SimpleCipherTest: XCTestCase { XCTAssertEqual(plaintext, cipher.decode(cipher.encode(plaintext))) } -// MARK: TestIncorrectKey + // MARK: TestIncorrectKey func testCipherWithCapsKey() { XCTAssertNil(Cipher(key: "ABCDEF")) @@ -39,7 +38,7 @@ class SimpleCipherTest: XCTestCase { XCTAssertNil(Cipher(key: "")) } -// MARK: TestSubstitution + // MARK: TestSubstitution let cipherSubstitution = Cipher(key: "abcdefghij") ?? Cipher() @@ -76,7 +75,7 @@ class SimpleCipherTest: XCTestCase { XCTAssertEqual(ciphertext, cipherSubstitution.encode(plaintext)) } -// MARK: TestPseudoShift + // MARK: TestPseudoShift let cipherPseudo = Cipher(key: "dddddddddd") ?? Cipher() diff --git a/exercises/simple-linked-list/SimpleLinkedListExample.swift b/exercises/simple-linked-list/SimpleLinkedListExample.swift index 39a8de3ce..7a010c92b 100644 --- a/exercises/simple-linked-list/SimpleLinkedListExample.swift +++ b/exercises/simple-linked-list/SimpleLinkedListExample.swift @@ -1,62 +1,48 @@ -// Foundation not needed +private extension Array { - - -private extension Array{ - - func reversedCustom()->Array{ - #if swift(>=3.0) + func reversedCustom() -> Array { return reversed() - #else - return reverse() - #endif + } } class Element { var value: T? = nil var next: Element? = nil - + init() { } - - init(_ value: T, _ next:Element?) { + + init(_ value: T, _ next: Element?) { self.value = value self.next = next } - - - func toArray () ->[T] { + func toArray () -> [T] { return toA(self) } - - private var countArray:Array = [] - - private func toA(input:Element, _ tempArray:Array = []) ->[T]{ + + private var countArray: Array = [] + + @discardableResult + private func toA(_ input: Element, _ tempArray: Array = []) -> [T] { if tempArray.isEmpty && input.value != nil { countArray.append(input.value!) } - if input.next != nil && input.next!.value != nil{ + if input.next != nil && input.next!.value != nil { countArray.append(input.next!.value!) toA(input.next!, countArray) } return countArray } - - - - class func fromArray(input:[T]) ->Element { + + class func fromArray(_ input: [T]) -> Element { var tempElement = Element() - for each in Array(input.reversedCustom()){ + for each in Array(input.reversedCustom()) { tempElement = Element(each, tempElement) } return tempElement } - - - - func reverseElements() -> Element { + + func reverseElements() -> Element { return Element.fromArray(Array(toArray().reversedCustom())) } - - -} \ No newline at end of file +} diff --git a/exercises/simple-linked-list/SimpleLinkedListTest.swift b/exercises/simple-linked-list/SimpleLinkedListTest.swift index d661698aa..7930383e3 100644 --- a/exercises/simple-linked-list/SimpleLinkedListTest.swift +++ b/exercises/simple-linked-list/SimpleLinkedListTest.swift @@ -1,12 +1,10 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif // Use Optionals and Generic Classes - class SimpleLinkedListTest: XCTestCase { - + func testConstructorA() { let one = Element(1, nil) let two = Element(2, one) @@ -14,7 +12,7 @@ class SimpleLinkedListTest: XCTestCase { XCTAssertNil(one.next) XCTAssertEqual(2, two.value!) } - + func testConstructorB() { let one = Element(1, nil) let two = Element(2, one) @@ -22,26 +20,26 @@ class SimpleLinkedListTest: XCTestCase { let result2 = two.next?.value XCTAssertEqual(result!, result2!) } - + func testToA() { let elementNil = Element() let elementOne = Element(1, nil) let elementTwo = Element(2, elementOne) let elementThree = Element(3, elementTwo) - XCTAssertEqual([] , elementNil.toArray() ) - XCTAssertEqual([1] , elementOne.toArray() ) - XCTAssertEqual([2, 1] , elementTwo.toArray() ) - XCTAssertEqual([3, 2, 1] , elementThree.toArray()) + XCTAssertEqual([], elementNil.toArray() ) + XCTAssertEqual([1], elementOne.toArray() ) + XCTAssertEqual([2, 1], elementTwo.toArray() ) + XCTAssertEqual([3, 2, 1], elementThree.toArray()) } - + func testReverseOne() { let one = Element(1, nil) let oneR = one.reverseElements() XCTAssertEqual(1, oneR.value!) XCTAssertNil(oneR.next?.value) - + } - + func testReverseTwo() { let one = Element(1, nil) let two = Element(2, one) @@ -50,36 +48,36 @@ class SimpleLinkedListTest: XCTestCase { let expect = twoR.next?.value XCTAssertEqual(2, expect!) } - + func testFromAOne() { - + XCTAssertNil(Element.fromArray([]).value) let oneA = Element.fromArray([1]) XCTAssertEqual(1, oneA.value!) XCTAssertNil(oneA.next?.value) - + } - + func testFromATwo() { - + let twoA = Element.fromArray([2, 1]) XCTAssertEqual(2, twoA.value!) let expected = twoA.next?.value XCTAssertEqual(1, expected! ) XCTAssertNil(twoA.next?.next?.value) } - + func testFromATen() { - + let oneToTen = Element.fromArray(Array(1...10)) let expected10 = oneToTen.next?.next?.next?.next?.next?.next?.next?.next?.next?.value XCTAssertEqual(10, expected10! ) } - + func testRoundtrip() { XCTAssertEqual([1], Element.fromArray([1]).toArray() ) XCTAssertEqual([2, 1], Element.fromArray([2, 1]).toArray() ) XCTAssertEqual(Array(1...10), Element.fromArray(Array(1...10)).toArray()) } - -} \ No newline at end of file + +} diff --git a/exercises/space-age/SpaceAgeExample.swift b/exercises/space-age/SpaceAgeExample.swift index 1c418006b..794958c60 100644 --- a/exercises/space-age/SpaceAgeExample.swift +++ b/exercises/space-age/SpaceAgeExample.swift @@ -1,26 +1,21 @@ import Darwin +struct SpaceAge { + var seconds: Float = 0 + + var onMercury: Float { get { return round((seconds / 7_600_530.24)*100)/100}} + var onVenus: Float { get { return round((seconds / 19_413_907.2)*100)/100}} + var onEarth: Float { get { return round((seconds / 31_558_149.76)*100)/100}} + var onMars: Float { get { return round((seconds / 59_354_294.4)*100)/100}} + var onJupiter: Float { get { return round((seconds / 374_335_776.0)*100)/100}} + var onSaturn: Float { get { return round((seconds / 929_596_608.0)*100)/100}} + var onUranus: Float { get { return round((seconds / 2_661_041_808.0)*100)/100}} + var onNeptune: Float { get { return round((seconds / 5_200_418_592.0)*100)/100}} + init(_ input: Float) { -struct SpaceAge{ - - var seconds:Float = 0 - - var onMercury:Float { get { return round((seconds / 7_600_530.24)*100)/100}} - var onVenus:Float { get { return round((seconds / 19_413_907.2)*100)/100}} - var onEarth:Float { get { return round((seconds / 31_558_149.76)*100)/100}} - var onMars:Float { get { return round((seconds / 59_354_294.4)*100)/100}} - var onJupiter:Float { get { return round((seconds / 374_335_776.0)*100)/100}} - var onSaturn:Float { get { return round((seconds / 929_596_608.0)*100)/100}} - var onUranus:Float { get { return round((seconds / 2_661_041_808.0)*100)/100}} - var onNeptune:Float { get { return round((seconds / 5_200_418_592.0)*100)/100}} - - - init(_ input:Float){ - self.seconds = input - + } - -} +} diff --git a/exercises/space-age/SpaceAgeTest.swift b/exercises/space-age/SpaceAgeTest.swift index 1a2c38b32..79e513788 100644 --- a/exercises/space-age/SpaceAgeTest.swift +++ b/exercises/space-age/SpaceAgeTest.swift @@ -1,60 +1,59 @@ - -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class SpaceAgeTest: XCTestCase { - + func testAgeInSeconds() { let age = SpaceAge(1_000_000) XCTAssertTrue(1_000_000 == age.seconds) } - + func testAgeInEarthYears() { let age = SpaceAge(1_000_000_000) XCTAssertTrue(31.69 == age.onEarth) } - + func testAgeInMercuryYears() { let age = SpaceAge(2_134_835_688) XCTAssertTrue(67.65 == age.onEarth) XCTAssertTrue(280.88 == age.onMercury) } - + func testAgeInVenusYears() { let age = SpaceAge(189_839_836) XCTAssertTrue(6.02 == age.onEarth) XCTAssertTrue(9.78 == age.onVenus) } - + func testAgeOnMars() { let age = SpaceAge(2_329_871_239) XCTAssertTrue(73.83 == age.onEarth) XCTAssertTrue(39.25 == age.onMars) } - + func testAgeOnJupiter() { let age = SpaceAge(901_876_382) XCTAssertTrue(28.58 == age.onEarth) XCTAssertTrue(2.41 == age.onJupiter) } - + func testAgeOnSaturn() { let age = SpaceAge(3_000_000_000) XCTAssertTrue(95.06 == age.onEarth) XCTAssertTrue(3.23 == age.onSaturn) } - + func testAgeOnUranus() { let age = SpaceAge(3_210_123_456) XCTAssertTrue(101.72 == age.onEarth) XCTAssertTrue(1.21 == age.onUranus) } - + func testAgeOnNeptune() { let age = SpaceAge(8_210_123_456) XCTAssertTrue(260.16 == age.onEarth) XCTAssertTrue(1.58 == age.onNeptune) } - -} \ No newline at end of file + +} diff --git a/exercises/strain/StrainExample.swift b/exercises/strain/StrainExample.swift index b8b27bf1c..07a2aaf9a 100644 --- a/exercises/strain/StrainExample.swift +++ b/exercises/strain/StrainExample.swift @@ -1,19 +1,15 @@ -// Foundation not needed +extension Array { - - -extension Array{ - - func keep(compare compare:Bool = true, inputFunc:(Element) -> Bool )->Array { - var array2Return:Array = [] - for each in self{ - if inputFunc(each) == compare{ + func keep(compare: Bool = true, inputFunc: (Element) -> Bool ) -> Array { + var array2Return: Array = [] + for each in self { + if inputFunc(each) == compare { array2Return.append(each)} - } + } return array2Return } - - func discard(inputFunc:(Element) -> Bool)->Array{ + + func discard(_ inputFunc: (Element) -> Bool) -> Array { return keep(compare: false, inputFunc: inputFunc) } -} \ No newline at end of file +} diff --git a/exercises/strain/StrainTest.swift b/exercises/strain/StrainTest.swift index 5f455f236..032a09188 100644 --- a/exercises/strain/StrainTest.swift +++ b/exercises/strain/StrainTest.swift @@ -1,32 +1,32 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif class StrainTest: XCTestCase { - + func testEmptyKeep() { - - XCTAssertTrue ([].keep{each -> Bool in each < 10}.isEmpty) + + XCTAssertTrue ([].keep {each -> Bool in each < 10}.isEmpty) } - + func testKeepEverything() { - XCTAssertEqual([1, 2, 3], [1, 2, 3].keep{each -> Bool in each < 10}) + XCTAssertEqual([1, 2, 3], [1, 2, 3].keep {each -> Bool in each < 10}) } - + func testKeepFirstAndLast() { - XCTAssertEqual([1, 3], [1, 2, 3].keep{ each -> Bool in (each % 2 != 0)}) + XCTAssertEqual([1, 3], [1, 2, 3].keep { each -> Bool in (each % 2 != 0)}) } - + func testKeepNeitherFirstNorLast() { - XCTAssertEqual([2, 4], [1, 2, 3, 4, 5].keep{ each -> Bool in (each % 2 == 0) }) + XCTAssertEqual([2, 4], [1, 2, 3, 4, 5].keep { each -> Bool in (each % 2 == 0) }) } - + func testKeepStrings() { let words = ["apple", "zebra", "banana", "zombies", "cherimoya", "zealot"] - let result = words.keep{each -> Bool in (each as String).hasPrefix("z") ?? false} + let result = words.keep {each -> Bool in (each as String).hasPrefix("z") ?? false} XCTAssertEqual(["zebra", "zombies", "zealot"], result) } - + func testKeepArrays () { let rows = [ [1, 2, 3], @@ -37,32 +37,32 @@ class StrainTest: XCTestCase { [2, 2, 1], [1, 2, 5] ] - let result = rows.keep{ each -> Bool in (each as [Int]).contains(5)} + let result = rows.keep { each -> Bool in (each as [Int]).contains(5)} XCTAssertEqual([[5, 5, 5], [5, 1, 2], [1, 5, 2], [1, 2, 5]], result) } - + func testEmptyDiscard() { XCTAssertEqual([], [].discard {each -> Bool in each < 10}) } - + func testDiscardNothing() { XCTAssertEqual([1, 2, 3], [1, 2, 3].discard {each -> Bool in each > 10}) } - + func testDiscardFirstAndLast() { XCTAssertEqual([2], [1, 2, 3].discard {each -> Bool in (each % 2 != 0)}) } - + func testDiscardNeitherFirstNorLast() { - XCTAssertEqual([1, 3, 5], [1, 2, 3, 4, 5].discard{ each -> Bool in (each % 2 == 0)}) + XCTAssertEqual([1, 3, 5], [1, 2, 3, 4, 5].discard { each -> Bool in (each % 2 == 0)}) } - + func testDiscardStrings() { let words = ["apple", "zebra", "banana", "zombies", "cherimoya", "zealot"] - let result = words.discard{each -> Bool in (each as String).hasPrefix("z") ?? false} + let result = words.discard {each -> Bool in (each as String).hasPrefix("z") ?? false} XCTAssertEqual(["apple", "banana", "cherimoya"], result) } - + func testDiscardArrays () { let rows = [ [1, 2, 3], @@ -76,6 +76,5 @@ class StrainTest: XCTestCase { let result = rows.discard { each -> Bool in (each as [Int]).contains(5)} XCTAssertEqual([[1, 2, 3], [2, 1, 2], [2, 2, 1]], result) } - -} +} diff --git a/exercises/sum-of-multiples/SumOfMultiplesExample.swift b/exercises/sum-of-multiples/SumOfMultiplesExample.swift index 08d1d8ffe..a5173c79e 100644 --- a/exercises/sum-of-multiples/SumOfMultiplesExample.swift +++ b/exercises/sum-of-multiples/SumOfMultiplesExample.swift @@ -1,16 +1,14 @@ -// Foundation not needed - struct SumOfMultiples { - - static func toLimit(limit: Int, inMultiples: [Int]) -> Int { + + static func toLimit(_ limit: Int, inMultiples: [Int]) -> Int { var multiples = Set(inMultiples) - - if let indexOfZero = multiples.indexOf(0) { - multiples.removeAtIndex(indexOfZero) + + if let indexOfZero = multiples.index(of: 0) { + multiples.remove(at: indexOfZero) } - + var itemToReturn = 0 - + for each in 1..=3.0) + import XCTest +#endif + +class SumOfMultiplesTest: XCTestCase { -class SumOfMultiplesTest:XCTestCase { - func testSumTo1() { XCTAssertEqual(0, SumOfMultiples.toLimit(1, inMultiples: [3, 5])) } - + func testSumTo3() { XCTAssertEqual(3, SumOfMultiples.toLimit(4, inMultiples: [3, 5])) } - + func testSumTo10() { XCTAssertEqual(23, SumOfMultiples.toLimit(10, inMultiples: [3, 5])) } @@ -17,23 +19,23 @@ class SumOfMultiplesTest:XCTestCase { func testSumTo100() { XCTAssertEqual(2318, SumOfMultiples.toLimit(100, inMultiples: [3, 5])) } - + func testSumTo1000() { XCTAssertEqual(233168, SumOfMultiples.toLimit(1000, inMultiples: [3, 5])) } - + func testConfigurable_7_13_17_to_20() { XCTAssertEqual(51, SumOfMultiples.toLimit(20, inMultiples: [7, 13, 17])) } - + func testConfigurable_4_6_to_15() { XCTAssertEqual(30, SumOfMultiples.toLimit(15, inMultiples: [4, 6])) } - + func testConfigurable_5_6_8_to_150() { XCTAssertEqual(4419, SumOfMultiples.toLimit(150, inMultiples: [5, 6, 8])) } - + func testConfigurable_43_47_to_10000() { XCTAssertEqual(2203160, SumOfMultiples.toLimit(10000, inMultiples: [43, 47])) } @@ -45,5 +47,5 @@ class SumOfMultiplesTest:XCTestCase { func testConfigurable_0_1_to_10() { XCTAssertEqual(45, SumOfMultiples.toLimit(10, inMultiples: [0, 1])) } - + } diff --git a/exercises/tournament/TournamentExample.swift b/exercises/tournament/TournamentExample.swift index 21e5e693b..dcf16421a 100644 --- a/exercises/tournament/TournamentExample.swift +++ b/exercises/tournament/TournamentExample.swift @@ -1,28 +1,26 @@ import Darwin - - private extension String { - - func trimWhiteSpace()-> String{ + + func trimWhiteSpace() -> String { let removeSpaces = trimCharacters(" ", sourceText: self) - if removeSpaces.hasSuffix("\n"){ + if removeSpaces.hasSuffix("\n") { return String(removeSpaces.characters.dropLast()) } return removeSpaces - + } - - func trimCharacters(charToTrim:Character, sourceText:String) -> String{ + + func trimCharacters(_ charToTrim: Character, sourceText: String) -> String { var editCharacterView = sourceText.characters var editString = String(editCharacterView) - + let trimFirst = sourceText.characters.first == charToTrim let trimLast = sourceText.characters.last == charToTrim - + if trimFirst { editCharacterView = editCharacterView.dropFirst() } if trimLast { editCharacterView = editCharacterView.dropLast() } - + if trimFirst || trimLast == true { editString = trimCharacters(charToTrim, sourceText: String(editCharacterView)) } @@ -30,187 +28,159 @@ private extension String { } } -struct Tournament -{ - enum Outcome - { - case LOSS - case DRAW - case WIN - case ERR +struct Tournament { + enum Outcome { + case loss + case draw + case win + case err } - - struct TeamResult - { - var Losses:Int = 0 - var Draws:Int = 0 - var Wins:Int = 0 - - var Played:Int { - return Losses + Draws + Wins + + struct TeamResult { + var losses: Int = 0 + var draws: Int = 0 + var wins: Int = 0 + + var played: Int { + return losses + draws + wins } - - var Score:Int { - return Wins * 3 + Draws + + var score: Int { + return wins * 3 + draws } - - mutating func addOutcome( outcome:Outcome )-> Void - { + + mutating func addOutcome( _ outcome: Outcome ) -> Void { switch outcome { - case .LOSS : - Losses += 1 - case .DRAW : - Draws += 1 - case .WIN : - Wins += 1 + case .loss : + losses += 1 + case .draw : + draws += 1 + case .win : + wins += 1 default : print("Error addOutcome") } } } - + private var teams = Dictionary() - - - private mutating func addResult(team1 team1:String, team2:String, outcome:Outcome) -> Void - { + private mutating func addResult(team1: String, team2: String, outcome: Outcome) -> Void { // Invert outcome for the second team. - let outcome2:Outcome = (outcome == Outcome.WIN) ? Outcome.LOSS : - (outcome == Outcome.LOSS) ? Outcome.WIN : - Outcome.DRAW - - + let outcome2: Outcome = (outcome == Outcome.win) ? Outcome.loss : + (outcome == Outcome.loss) ? Outcome.win : + Outcome.draw addTeamOutcome(team1, outcome) addTeamOutcome(team2, outcome2) } - + private var teamResult = TeamResult() - - private mutating func addTeamOutcome(team:String, _ outcome:Outcome) -> Void - { + + private mutating func addTeamOutcome(_ team: String, _ outcome: Outcome) -> Void { if teams[team] != nil { teamResult = teams[team]! teamResult.addOutcome(outcome) teams[team] = teamResult - + } else { teamResult = TeamResult() teamResult.addOutcome(outcome) teams[team] = teamResult } } - - private mutating func writeResults()-> String - { - - func formarter (Team:String, MP:String, W:String, D:String, L:String, P:String)->String{ - - func wsChars(text:String, spacing:Int = 31)->String{ - return Repeat(count:abs(spacing - Array(text.characters).count) , repeatedValue: " ").joinWithSeparator("") + + private mutating func writeResults() -> String { + + func formarter (_ team: String, mp: String, w: String, d: String, l: String, p: String) -> String { + + func wsChars(_ text: String, spacing: Int = 31) -> String { + return repeatElement( " ", count: abs(spacing - Array(text.characters).count)).joined(separator: "") + } - - func spacing(text:String, columnWith:Int = 4)->String{ + + func spacing(_ text: String, columnWith: Int = 4) -> String { let textCount = Array(text.characters).count let space = Int(round(Double(textCount) / Double(columnWith))) - + return wsChars(text, spacing: columnWith - space - textCount) + text + wsChars(text, spacing: space ) } - - let text = "\(Team)" + wsChars(Team) + "|" + spacing(MP) + "|" + spacing(W) + "|" + spacing(D) + "|" + spacing(L) + "|" + spacing(P) - + + let text = "\(team)" + wsChars(team) + "|" + spacing(mp) + "|" + spacing(w) + "|" + spacing(d) + "|" + spacing(l) + "|" + spacing(p) + return text.trimWhiteSpace() + "\n" - + } - - var textOutput:String = "" - - let header = formarter("Team", MP: "MP", W: "W", D: "D", L: "L", P: "P") - + + var textOutput: String = "" + + let header = formarter("Team", mp: "MP", w: "W", d: "D", l: "L", p: "P") + textOutput += header - - - func sortKeysByValue()->[String] - { + func sortKeysByValue() -> [String] { var sortByValue = [(String, Int)]() - for each in Array(teams.keys){ + for each in Array(teams.keys) { let tempVal = teams[each]! - sortByValue.append((each, tempVal.Score)) + sortByValue.append((each, tempVal.score)) } - sortByValue.sortInPlace{$0.1 > $1.1} + sortByValue.sort {$0.1 > $1.1} var sortedKeys = [String]() - for each in sortByValue{ + for each in sortByValue { sortedKeys.append(each.0) } - + return sortedKeys } - - for team in sortKeysByValue(){ - + + for team in sortKeysByValue() { + let result = teams[team]! - - let MP = result.Played - let W = result.Wins - let D = result.Draws - let L = result.Losses - let P = result.Score - - + + let mp = result.played + let w = result.wins + let d = result.draws + let l = result.losses + let p = result.score let line = formarter(team, - MP: "\(MP)", - W: "\(W)", - D: "\(D)", - L: "\(L)", - P: "\(P)") - + mp: "\(mp)", + w: "\(w)", + d: "\(d)", + l: "\(l)", + p: "\(p)") + textOutput += line } return textOutput.trimWhiteSpace() } - - func tally(inStream:String) -> String - { + + func tally(_ inStream: String) -> String { // Create New Tournament var tournament = Tournament() - - var outcome:Outcome = Outcome.ERR - + + var outcome: Outcome = Outcome.err + // alternative to .componentsSeparatedByString let textArrayLines = inStream.characters.split {$0 == "\n"}.map { String($0) } - - for line in textArrayLines - { - let parts = line.trimWhiteSpace().componentsSeparatedByString(";") - if parts.count == 3 - { - switch parts[2].lowercaseString - { + + for line in textArrayLines { + let parts = line.trimWhiteSpace().components(separatedBy: ";") + if parts.count == 3 { + switch parts[2].lowercased() { case "loss": - outcome = Outcome.LOSS + outcome = Outcome.loss case "draw": - outcome = Outcome.DRAW + outcome = Outcome.draw case "win": - outcome = Outcome.WIN + outcome = Outcome.win default: - outcome = Outcome.ERR + outcome = Outcome.err } - - if outcome != Outcome.ERR - { + + if outcome != Outcome.err { tournament.addResult(team1: parts[0], team2: parts[1], outcome: outcome) } } } - + return tournament.writeResults() } - - - -} - - - - - +} diff --git a/exercises/tournament/TournamentTest.swift b/exercises/tournament/TournamentTest.swift index 21f58cde1..cdeaac457 100644 --- a/exercises/tournament/TournamentTest.swift +++ b/exercises/tournament/TournamentTest.swift @@ -1,19 +1,18 @@ -import XCTest +#if swift(>=3.0) + import XCTest +#endif +class TournamentTest: XCTestCase { - - -class TournamentTest:XCTestCase { - - let input1 = + let input1 = "Allegoric Alaskians;Blithering Badgers;win\n" + "Devastating Donkeys;Courageous Californians;draw\n" + "Devastating Donkeys;Allegoric Alaskians;win\n" + "Courageous Californians;Blithering Badgers;loss\n" + "Blithering Badgers;Devastating Donkeys;loss\n" + - "Allegoric Alaskians;Courageous Californians;win" - - let input2 = + "Allegoric Alaskians;Courageous Californians;win" + + let input2 = "Allegoric Alaskians;Blithering Badgers;win\n" + "Devastating Donkeys_Courageous Californians;draw\n" + "Devastating Donkeys;Allegoric Alaskians;win\n" + @@ -23,51 +22,47 @@ class TournamentTest:XCTestCase { "Blithering Badgers;Devastating Donkeys;loss\n" + "# Yackity yackity yack\n" + "Allegoric Alaskians;Courageous Californians;win\n" + - "Devastating Donkeys;Courageous Californians;draw" - - let input3 = + "Devastating Donkeys;Courageous Californians;draw" + + let input3 = "Allegoric Alaskians;Blithering Badgers;win\n" + "Devastating Donkeys;Allegoric Alaskians;win\n" + "Courageous Californians;Blithering Badgers;loss\n" + - "Allegoric Alaskians;Courageous Californians;win" - - - let expected1 = - "Team | MP | W | D | L | P\n" + + "Allegoric Alaskians;Courageous Californians;win" + let expected1 = + "Team | MP | W | D | L | P\n" + "Devastating Donkeys | 3 | 2 | 1 | 0 | 7\n" + "Allegoric Alaskians | 3 | 2 | 0 | 1 | 6\n" + "Blithering Badgers | 3 | 1 | 0 | 2 | 3\n" + - "Courageous Californians | 3 | 0 | 1 | 2 | 1" - - let expected2 = - "Team | MP | W | D | L | P\n" + + "Courageous Californians | 3 | 0 | 1 | 2 | 1" + + let expected2 = + "Team | MP | W | D | L | P\n" + "Devastating Donkeys | 3 | 2 | 1 | 0 | 7\n" + "Allegoric Alaskians | 3 | 2 | 0 | 1 | 6\n" + "Blithering Badgers | 3 | 1 | 0 | 2 | 3\n" + - "Courageous Californians | 3 | 0 | 1 | 2 | 1" - - let expected3 = - "Team | MP | W | D | L | P\n" + + "Courageous Californians | 3 | 0 | 1 | 2 | 1" + + let expected3 = + "Team | MP | W | D | L | P\n" + "Allegoric Alaskians | 3 | 2 | 0 | 1 | 6\n" + "Blithering Badgers | 2 | 1 | 0 | 1 | 3\n" + "Devastating Donkeys | 1 | 1 | 0 | 0 | 3\n" + - "Courageous Californians | 2 | 0 | 0 | 2 | 0" - + "Courageous Californians | 2 | 0 | 0 | 2 | 0" - func testGoodInput() { let tournament = Tournament() - XCTAssertEqual(tournament.tally(input1), expected1) + XCTAssertEqual(tournament.tally(input1), expected1) } func testIgnoreBadlines() { let tournament = Tournament() - XCTAssertEqual(tournament.tally(input2), expected2) + XCTAssertEqual(tournament.tally(input2), expected2) } - + func testinCompleteCompetition() { let tournament = Tournament() - XCTAssertEqual(tournament.tally(input3), expected3) + XCTAssertEqual(tournament.tally(input3), expected3) } } diff --git a/exercises/triangle/TriangleExample.swift b/exercises/triangle/TriangleExample.swift index 8bffb81b0..b37ecc101 100644 --- a/exercises/triangle/TriangleExample.swift +++ b/exercises/triangle/TriangleExample.swift @@ -1,60 +1,52 @@ -// Foundation not needed - +let triangleKind = (Equilateral:"Equilateral", Isosceles:"Isosceles", Scalene:"Scalene", ErrorKind:"ErrorKind") +struct Triangle { + var a: Double = 0 + var b: Double = 0 + var c: Double = 0 -let triangleKind = (Equilateral:"Equilateral",Isosceles:"Isosceles",Scalene:"Scalene",ErrorKind:"ErrorKind") + var kind: String { get { return self.Kind() }} + init(_ a: Double, _ b: Double, _ c: Double) { + (self.a, self.b, self.c) = (a, b, c) -struct Triangle { - - var a:Double = 0 - var b:Double = 0 - var c:Double = 0 - - var kind:String { get { return self.Kind() }} - - init(_ a:Double, _ b:Double, _ c:Double){ - (self.a,self.b,self.c) = (a,b,c) - } - - func uniqueSides() -> Int{ + + func uniqueSides() -> Int { var tempSet = Set() - for each in [a,b,c]{ - tempSet.insert(each) + for each in [a, b, c] { + tempSet.insert(each) } - + return tempSet.count } - - - func allSidesAreZero() -> Bool{ + func allSidesAreZero() -> Bool { return a == 0 && b == 0 && c == 0 } - - func hasImpossibleSides() -> Bool{ + + func hasImpossibleSides() -> Bool { return a < 0 || b < 0 || c < 0 } - - func violatesTriangleInequality() -> Bool{ + + func violatesTriangleInequality() -> Bool { return a + b < c || a + c < b || b + c < a } - - func Kind()->String{ - + + func Kind() -> String { + if (allSidesAreZero() || hasImpossibleSides() || violatesTriangleInequality()) { return triangleKind.ErrorKind } - + let unique = uniqueSides() - - if (unique == 1){ + + if (unique == 1) { return triangleKind.Equilateral} - - if (unique == 2){ + + if (unique == 2) { return triangleKind.Isosceles} - + return triangleKind.Scalene } - -} \ No newline at end of file + +} diff --git a/exercises/triangle/TriangleTest.swift b/exercises/triangle/TriangleTest.swift index 17a41e57e..d6746ba03 100644 --- a/exercises/triangle/TriangleTest.swift +++ b/exercises/triangle/TriangleTest.swift @@ -1,71 +1,63 @@ -import XCTest - - - +#if swift(>=3.0) + import XCTest +#endif class TriangleTest: XCTestCase { - - let triangleKind = (Equilateral:"Equilateral",Isosceles:"Isosceles",Scalene:"Scalene",ErrorKind:"ErrorKind") - - + + let triangleKind = (Equilateral:"Equilateral", Isosceles:"Isosceles", Scalene:"Scalene", ErrorKind:"ErrorKind") func testEquilateralTrianglesHaveEqualSides() { - XCTAssertEqual(triangleKind.Equilateral, Triangle(2, 2, 2).kind) + XCTAssertEqual(triangleKind.Equilateral, Triangle(2, 2, 2).kind) } - + func testLargerEquilateralTrianglesAlsoHaveEqualSides() { - XCTAssertEqual(triangleKind.Equilateral, Triangle(10, 10, 10).kind) + XCTAssertEqual(triangleKind.Equilateral, Triangle(10, 10, 10).kind) } - + func testIsoscelesTrianglesHaveLastTwoSidesEqual() { - XCTAssertEqual(triangleKind.Isosceles, Triangle(3, 4, 4).kind) + XCTAssertEqual(triangleKind.Isosceles, Triangle(3, 4, 4).kind) } - + func testIsoscelesTrianglesHaveFirstAndLastSidesEqual() { - XCTAssertEqual(triangleKind.Isosceles, Triangle(4, 3, 4).kind) + XCTAssertEqual(triangleKind.Isosceles, Triangle(4, 3, 4).kind) } - + func testIsoscelesTrianglesHaveTwoFirstSidesEqual() { - XCTAssertEqual(triangleKind.Isosceles, Triangle(4, 4, 3).kind) + XCTAssertEqual(triangleKind.Isosceles, Triangle(4, 4, 3).kind) } - + func testIsoscelesTrianglesHaveInFactExactlyTwoSidesEqual() { - XCTAssertEqual(triangleKind.Isosceles, Triangle(10, 10, 2).kind) + XCTAssertEqual(triangleKind.Isosceles, Triangle(10, 10, 2).kind) } - + func testScaleneTrianglesHaveNoEqualSides() { - XCTAssertEqual(triangleKind.Scalene, Triangle(3, 4, 5).kind) + XCTAssertEqual(triangleKind.Scalene, Triangle(3, 4, 5).kind) } - + func testScaleneTrianglesHaveNoEqualSidesAtALargerScaleToo() { - XCTAssertEqual(triangleKind.Scalene, Triangle(10, 11, 12).kind) + XCTAssertEqual(triangleKind.Scalene, Triangle(10, 11, 12).kind) } - + func testScaleneTrianglesHaveNoEqualSidesInDescendingOrderEither() { - XCTAssertEqual(triangleKind.Scalene, Triangle(5, 4, 2).kind) + XCTAssertEqual(triangleKind.Scalene, Triangle(5, 4, 2).kind) } - + func testVerySmallTrianglesAreLegal() { - XCTAssertEqual(triangleKind.Scalene, Triangle(0.4, 0.6, 0.3).kind) + XCTAssertEqual(triangleKind.Scalene, Triangle(0.4, 0.6, 0.3).kind) } - + func testTrianglesWithNoSizeAreIllegal() { - XCTAssertEqual(triangleKind.ErrorKind, Triangle(0, 0, 0).kind) + XCTAssertEqual(triangleKind.ErrorKind, Triangle(0, 0, 0).kind) } - + func testTrianglesWithNegativeSidesAreIllegal() { - XCTAssertEqual(triangleKind.ErrorKind, Triangle(3, 4, -5).kind) + XCTAssertEqual(triangleKind.ErrorKind, Triangle(3, 4, -5).kind) } - + func testTrianglesViolatingTriangleInequalityAreIllegal() { - XCTAssertEqual(triangleKind.ErrorKind, Triangle(1, 1, 3).kind) + XCTAssertEqual(triangleKind.ErrorKind, Triangle(1, 1, 3).kind) } - - - + func testTrianglesViolatingTriangleInequalityAreIllegal3() { - XCTAssertEqual(triangleKind.ErrorKind, Triangle(7, 3, 2).kind) + XCTAssertEqual(triangleKind.ErrorKind, Triangle(7, 3, 2).kind) } - - } - diff --git a/exercises/trinary/TrinaryExample.swift b/exercises/trinary/TrinaryExample.swift index e1214e6e5..63b3383ee 100644 --- a/exercises/trinary/TrinaryExample.swift +++ b/exercises/trinary/TrinaryExample.swift @@ -1,46 +1,36 @@ import Darwin - - -extension Int{ - init(_ value:Trinary){ +extension Int { + init(_ value: Trinary) { self = value.toDecimal } } - - struct Trinary { - private var stringValue = "" - private var toDecimal:Int = 0 - private func isValidTrinary() -> Bool{ + private var stringValue = "" + private var toDecimal: Int = 0 + private func isValidTrinary() -> Bool { return (Int(stringValue) ?? -1) > -1 ? true : false } - - private func tri2int(input:String)->Int{ - #if swift(>=3.0) + + private func tri2int(_ input: String) -> Int { let orderedInput = Array(input.characters.reversed()) let enumarated = orderedInput.enumerated() - #else - let orderedInput = Array(input.characters.reverse()) - let enumarated = orderedInput.enumerate() - #endif - var tempInt:Int = 0 - for (inx,each) in enumarated{ + + var tempInt: Int = 0 + for (inx, each) in enumarated { let tempCharInt = Int("\(each)") ?? 0 - let tempTriPower = Int(pow(Double(3),Double(inx))) - tempInt += tempTriPower * tempCharInt + let tempTriPower = Int(pow(Double(3), Double(inx))) + tempInt += tempTriPower * tempCharInt } return tempInt } - - - init( _ sv:String){ + init( _ sv: String) { self.stringValue = sv - + if isValidTrinary() { self.toDecimal = tri2int(sv) } - + } -} \ No newline at end of file +} diff --git a/exercises/trinary/TrinaryTest.swift b/exercises/trinary/TrinaryTest.swift index 668316c0b..f540d08e7 100644 --- a/exercises/trinary/TrinaryTest.swift +++ b/exercises/trinary/TrinaryTest.swift @@ -1,46 +1,42 @@ -import XCTest - - - +#if swift(>=3.0) + import XCTest +#endif class TrinaryTest: XCTestCase { - + func testTrinary1IsDecimal1() { XCTAssertEqual(1, Int(Trinary("1"))) } - + func testTrinary2IsDecimal2() { XCTAssertEqual(2, Int(Trinary("2"))) } - + func testTrinary10IsDecimal3() { XCTAssertEqual(3, Int(Trinary("10"))) } - + func testTrinary11IsDecimal4() { XCTAssertEqual(4, Int(Trinary("11"))) } - + func testTrinary100IsDecimal9() { XCTAssertEqual(9, Int(Trinary("100"))) } - + func testTrinary112IsDecimal14() { XCTAssertEqual(14, Int(Trinary("112"))) } - + func testTrinary222Is26() { XCTAssertEqual(26, Int(Trinary("222"))) } - + func testTrinary1122000120Is32091() { XCTAssertEqual(32091, Int(Trinary("1122000120"))) } - + func testInvalidTrinaryIsDecimal0() { XCTAssertEqual(0, Int(Trinary("carrot"))) } - - - } - +} diff --git a/exercises/twelve-days/TwelveDaysExample.swift b/exercises/twelve-days/TwelveDaysExample.swift index ef9a9a5d4..6be20d5cd 100644 --- a/exercises/twelve-days/TwelveDaysExample.swift +++ b/exercises/twelve-days/TwelveDaysExample.swift @@ -1,24 +1,19 @@ -// Foundation not needed - - - struct TwelveDaysSong { - - static func sing() -> String{ - return verses(1,12) + + static func sing() -> String { + return verses(1, 12) } - - static func verses(start:Int, _ end:Int) ->String{ + + static func verses(_ start: Int, _ end: Int) -> String { var string2return = "" - for each in start...end{ + for each in start...end { string2return += verse(each) + "\n" } - + return string2return } - static func verse(number:Int) ->String{ - switch(number) - { + static func verse(_ number: Int) -> String { + switch(number) { case 1: return "On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree.\n" case 2: @@ -47,5 +42,5 @@ struct TwelveDaysSong { return "" } } - -} \ No newline at end of file + +} diff --git a/exercises/twelve-days/TwelveDaysTest.swift b/exercises/twelve-days/TwelveDaysTest.swift index 33cd0caef..3973ca300 100644 --- a/exercises/twelve-days/TwelveDaysTest.swift +++ b/exercises/twelve-days/TwelveDaysTest.swift @@ -1,83 +1,80 @@ -import XCTest - - - +#if swift(>=3.0) + import XCTest +#endif class TwelveDaysTest: XCTestCase { - - func testVerse1() { let expected = "On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(1) XCTAssertEqual(expected, result) } - + func testVerse2() { let expected = "On the second day of Christmas my true love gave to me, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(2) XCTAssertEqual(expected, result) } - + func testVerse3() { let expected = "On the third day of Christmas my true love gave to me, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(3) XCTAssertEqual(expected, result) } - + func testVerse4() { let expected = "On the fourth day of Christmas my true love gave to me, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(4) XCTAssertEqual(expected, result) } - + func testVerse5() { let expected = "On the fifth day of Christmas my true love gave to me, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(5) XCTAssertEqual(expected, result) } - + func testVerse6() { let expected = "On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(6) XCTAssertEqual(expected, result) } - + func testVerse7() { let expected = "On the seventh day of Christmas my true love gave to me, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(7) XCTAssertEqual(expected, result) } - + func testVerse8() { let expected = "On the eighth day of Christmas my true love gave to me, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(8) XCTAssertEqual(expected, result) } - + func testVerse9() { let expected = "On the ninth day of Christmas my true love gave to me, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(9) XCTAssertEqual(expected, result) } - + func testVerse10() { let expected = "On the tenth day of Christmas my true love gave to me, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(10) XCTAssertEqual(expected, result) } - + func testVerse11() { let expected = "On the eleventh day of Christmas my true love gave to me, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(11) XCTAssertEqual(expected, result) } - + func testVerse12() { let expected = "On the twelfth day of Christmas my true love gave to me, twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(12) XCTAssertEqual(expected, result) } - + func testMultipleVerses() { let expected = ( "On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree.\n\n" + @@ -86,13 +83,11 @@ class TwelveDaysTest: XCTestCase { let result = TwelveDaysSong.verses(1, 3) XCTAssertEqual(expected, result) } - + func testTheWholeSong() { - + XCTAssertEqual(TwelveDaysSong.verses(1, 12), TwelveDaysSong.sing()) - + } - - - + } diff --git a/exercises/word-count/WordCountExample.swift b/exercises/word-count/WordCountExample.swift index 058fa4fe4..f87281f12 100644 --- a/exercises/word-count/WordCountExample.swift +++ b/exercises/word-count/WordCountExample.swift @@ -1,43 +1,37 @@ -// Foundation not needed - - - struct WordCount { - func splitStringToArray(inString:String) -> [String]{ - - return inString.characters.split(isSeparator: { splitAt($0) }).map{String($0)} + func splitStringToArray(_ inString: String) -> [String] { + + return inString.characters.split(isSeparator: { splitAt($0) }).map {String($0)} } - - func splitAt(characterToCompare:Character, charToSplitAt:String = " !&$%^&,:")-> Bool{ - for each in charToSplitAt.characters{ - if each == characterToCompare{ + + func splitAt(_ characterToCompare: Character, charToSplitAt: String = " !&$%^&,:") -> Bool { + for each in charToSplitAt.characters { + if each == characterToCompare { return true } } return false } - + let words: String - + init(words: String) { self.words = words } - + func count() -> [String: Int] { var dict = [String:Int]() let cleanArray = splitStringToArray(words) - + cleanArray.forEach { string in if !string.isEmpty { - if let count = dict[string.lowercaseString] { - dict[string.lowercaseString] = count + 1 - } else { dict[string.lowercaseString] = 1 - } + if let count = dict[string.lowercased()] { + dict[string.lowercased()] = count + 1 + } else { dict[string.lowercased()] = 1 } - } - return dict + } } + return dict + } } - - diff --git a/exercises/word-count/WordCountTest.swift b/exercises/word-count/WordCountTest.swift index 5208b4fa4..4f254a1e4 100644 --- a/exercises/word-count/WordCountTest.swift +++ b/exercises/word-count/WordCountTest.swift @@ -1,56 +1,55 @@ -import XCTest - - - +#if swift(>=3.0) + import XCTest +#endif class WordCountTest: XCTestCase { - + func testCountOneWord() { let words = WordCount(words: "word") let expected = ["word": 1] let result = words.count() - + XCTAssertEqual(expected, result) } - + func testCountOneOfEeach() { let words = WordCount(words: "one of each") let expected = ["one" : 1, "of" : 1, "each" : 1 ] - let result = words.count(); - + let result = words.count() + XCTAssertEqual(expected, result) } - + func testCountMultipleOccurrences() { let words = WordCount(words: "one fish two fish red fish blue fish") let expected = ["one" : 1, "fish" : 4, "two" : 1, "red" : 1, "blue" : 1 ] let result = words.count() - + XCTAssertEqual(expected, result) } - + func testIgnorePunctation() { let words = WordCount(words: "car : carpet as java : javascript!!&$%^&") let expected = ["car" : 1, "carpet" : 1, "as" : 1, "java" : 1, "javascript" : 1 ] let result = words.count() - + XCTAssertEqual(expected, result) } - + func testIncludeNumbers() { let words = WordCount(words: "testing, 1, 2 testing") let expected = [ "testing" : 2, "1" : 1, "2" : 1 ] let result = words.count() - + XCTAssertEqual(expected, result) } - + func testNormalizeCase() { let words = WordCount(words:"go Go GO") let expected = [ "go" : 3] let result = words.count() - + XCTAssertEqual(expected, result) } - + } diff --git a/exercises/wordy/WordyExample.swift b/exercises/wordy/WordyExample.swift index 7017f5f81..7e3d9752d 100644 --- a/exercises/wordy/WordyExample.swift +++ b/exercises/wordy/WordyExample.swift @@ -1,148 +1,117 @@ -// Foundation not needed - - - private extension String { - - func trimWhiteSpace()-> String{ + + func trimWhiteSpace() -> String { let removeSpaces = trimCharacters(" ", sourceText: self) - if removeSpaces.hasSuffix("\n"){ + if removeSpaces.hasSuffix("\n") { return String(removeSpaces.characters.dropLast()) } return removeSpaces } - - func trimCharacters(charToTrim:Character, sourceText:String) -> String{ + + func trimCharacters(_ charToTrim: Character, sourceText: String) -> String { var editCharacterView = sourceText.characters var editString = String(editCharacterView) - + let trimFirst = sourceText.characters.first == charToTrim let trimLast = sourceText.characters.last == charToTrim - + if trimFirst { editCharacterView = editCharacterView.dropFirst() } if trimLast { editCharacterView = editCharacterView.dropLast() } - + if trimFirst || trimLast == true { editString = trimCharacters(charToTrim, sourceText: String(editCharacterView)) } return editString } - - func replacingOccurrencesCustom(of:String, with: String) -> String { - #if swift(>=3.0) - return replacingOccurrences(of: of, with: with) - #else - return stringByReplacingOccurrencesOfString(of, withString: with) - #endif - } - - func componentsSeparatedByStringCustom(input:String)->Array { - #if swift(>=3.0) - return componentsSeparated(by: input) - #else - return componentsSeparatedByString(input) - #endif - } - -} + func replacingOccurrencesCustom(_ of: String, with: String) -> String { + return replacingOccurrences(of: of, with: with) -#if swift(>=3.0) - enum calculateError:ErrorProtocol{ - case error } -#else - enum calculateError:ErrorType{ - case error + + func componentsSeparatedByStringCustom(_ input: String)->Array { + return components(separatedBy: input) + } -#endif +} +enum CalculateError: ErrorProtocol { + case error +} struct WordProblem { var textIn = "" - - init(_ text:String){ + + init(_ text: String) { self.textIn = text } - + private let operans = ["plus" : "+", - "minus" : "-", - "multiplied by" : "*", - "divided by" : "/"] - + "minus" : "-", + "multiplied by" : "*", + "divided by" : "/"] + private let funcs = - ["+":{(a:Int, b:Int) -> Int in return a + b}, - "-":{(a:Int, b:Int) -> Int in return a - b}, - "*":{(a:Int, b:Int) -> Int in return a * b}, - "/":{(a:Int, b:Int) -> Int in return a / b}] - - - func answer() throws -> Int{ + ["+": {(a: Int, b: Int) -> Int in return a + b}, + "-": {(a: Int, b: Int) -> Int in return a - b}, + "*": {(a: Int, b: Int) -> Int in return a * b}, + "/": {(a: Int, b: Int) -> Int in return a / b}] + func answer() throws -> Int { guard let toReturn = calculate(textIn) else { - throw calculateError.error + throw CalculateError.error } return toReturn } - - func calculate(textIn:String) ->Int?{ + + func calculate(_ textIn: String) -> Int? { let calcStack = replaceText(textIn).componentsSeparatedByStringCustom(" ") - + if calcStack.count == 3 { let a = Int(calcStack[0]) let operA = funcs[calcStack[1]] let b = Int(calcStack[2]) - + if a != nil || operA != nil || b == nil { return operA!(a!, b!) } } - + if calcStack.count == 5 { let a = Int(calcStack[0]) let operA = funcs[calcStack[1]] let b = Int(calcStack[2]) let operB = funcs[calcStack[3]] let c = Int(calcStack[4]) - + if a != nil || operA != nil || b == nil || operB != nil || c != nil { - - let left = operA!(a!, b!) - return operB!(left, c!) } + + let left = operA!(a!, b!) + return operB!(left, c!) } } return nil } - - - private func replaceText( textInp:String)-> String{ + private func replaceText( _ textInp: String) -> String { var textInp = textInp - for key in Array(operans.keys){ + for key in Array(operans.keys) { let toBeReplaced = key let toReplaceValue = operans[key]! textInp = textInp.replacingOccurrencesCustom(toBeReplaced, with: toReplaceValue) } - - func checkCharInSet(input:Character)->Bool{ - #if swift(>=3.0) + + func checkCharInSet(_ input: Character) -> Bool { let temp = " 0987654321+-*/".characters.index(of: input) - #else - let temp = " 0987654321+-*/".characters.indexOf(input) - #endif + if temp == nil { return false } else { return true} } - + var newTextIn = Array(textInp.characters) newTextIn = newTextIn.filter(checkCharInSet) - let newTextInString:[String] = newTextIn.map{String($0)} - #if swift(>=3.0) + let newTextInString: [String] = newTextIn.map {String($0)} return newTextInString.joined(separator: "").trimWhiteSpace() - #else - return newTextInString.joinWithSeparator("").trimWhiteSpace() - #endif - } - -} \ No newline at end of file + } +} diff --git a/exercises/wordy/WordyTest.swift b/exercises/wordy/WordyTest.swift index 271b880c8..441613da9 100644 --- a/exercises/wordy/WordyTest.swift +++ b/exercises/wordy/WordyTest.swift @@ -1,74 +1,73 @@ -import XCTest - - +#if swift(>=3.0) + import XCTest +#endif // Use error handeling - class WordyTest: XCTestCase { - + func testAdd1() { XCTAssertEqual(2, try? WordProblem("What is 1 plus 1?").answer()) } - + func testAdd2() { XCTAssertEqual(55, try? WordProblem("What is 53 plus 2?").answer()) } - + func testAddNegativeNumbers() { XCTAssertEqual(-11, try? WordProblem("What is -1 plus -10?").answer()) } - + func testAddMoreDigits() { XCTAssertEqual(45_801, try? WordProblem("What is 123 plus 45678?").answer()) } - + func testSubtract() { XCTAssertEqual(16, try? WordProblem("What is 4 minus -12?").answer()) } - + func testMultiply() { XCTAssertEqual(-75, try? WordProblem("What is -3 multiplied by 25?").answer()) } - + func testDivide() { XCTAssertEqual(-11, try? WordProblem("What is 33 divided by -3?").answer()) } - + func testAddTwice() { let question = "What is 1 plus 1 plus 1?" XCTAssertEqual(3, try? WordProblem(question).answer()) } - + func testAddThenSubtract() { let question = "What is 1 plus 5 minus -2?" XCTAssertEqual(8, try? WordProblem(question).answer()) } - + func testSubtractTwice() { let question = "What is 20 minus 4 minus 13?" XCTAssertEqual(3, try? WordProblem(question).answer()) } - + func testSubtractThenAdd() { let question = "What is 17 minus 6 plus 3?" XCTAssertEqual(14, try? WordProblem(question).answer()) } - + func testMultiplyTwice() { let question = "What is 2 multiplied by -2 multiplied by 3?" XCTAssertEqual(-12, try? WordProblem(question).answer()) } - + func testAddThenMultiply() { let question = "What is -3 plus 7 multiplied by -2?" XCTAssertEqual(-8, try? WordProblem(question).answer()) } - + func testDivideTwice() { let question = "What is -12 divided by 2 divided by -3?" XCTAssertEqual(2, try? WordProblem(question).answer()) } - + func testTooAdvanced() { XCTAssertNil(try? WordProblem("What is 53 cubed?").answer()) } - + func testIrrelevant() { XCTAssertNil(try? WordProblem("Who is the president of the United States?").answer()) } - + } diff --git a/xcodeProject/xSwift.xcodeproj/project.pbxproj b/xcodeProject/xSwift.xcodeproj/project.pbxproj index 5bce56e7c..a128dd7a1 100755 --- a/xcodeProject/xSwift.xcodeproj/project.pbxproj +++ b/xcodeProject/xSwift.xcodeproj/project.pbxproj @@ -153,140 +153,140 @@ /* Begin PBXFileReference section */ 1E167A0F1C8AA5D7001EAD90 /* PokerExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PokerExample.swift; sourceTree = ""; }; - 1E167A101C8AA5D7001EAD90 /* PokerTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PokerTest.swift; sourceTree = ""; }; - 1E4CC79E1C90D48300C8BBEB /* DominoesExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DominoesExample.swift; sourceTree = ""; }; + 1E167A101C8AA5D7001EAD90 /* PokerTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = PokerTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E4CC79E1C90D48300C8BBEB /* DominoesExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = DominoesExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A62EA1C506EFC00E28AE1 /* AccumulateExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AccumulateExample.swift; sourceTree = ""; }; - 1E9A62EB1C506EFC00E28AE1 /* AccumulateTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AccumulateTest.swift; sourceTree = ""; }; + 1E9A62EB1C506EFC00E28AE1 /* AccumulateTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = AccumulateTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A62ED1C506EFC00E28AE1 /* AcronymExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AcronymExample.swift; sourceTree = ""; }; - 1E9A62EE1C506EFC00E28AE1 /* AcronymTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AcronymTest.swift; sourceTree = ""; }; + 1E9A62EE1C506EFC00E28AE1 /* AcronymTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = AcronymTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A62F01C506EFC00E28AE1 /* AllergiesExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AllergiesExample.swift; sourceTree = ""; }; - 1E9A62F11C506EFC00E28AE1 /* AllergiesTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AllergiesTest.swift; sourceTree = ""; }; + 1E9A62F11C506EFC00E28AE1 /* AllergiesTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = AllergiesTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A62F31C506EFC00E28AE1 /* AnagramExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnagramExample.swift; sourceTree = ""; }; - 1E9A62F41C506EFC00E28AE1 /* AnagramTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnagramTest.swift; sourceTree = ""; }; - 1E9A62F61C506EFC00E28AE1 /* AtbashExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AtbashExample.swift; sourceTree = ""; }; - 1E9A62F71C506EFC00E28AE1 /* AtbashTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AtbashTest.swift; sourceTree = ""; }; - 1E9A62F91C506EFC00E28AE1 /* BinaryExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BinaryExample.swift; sourceTree = ""; }; - 1E9A62FA1C506EFC00E28AE1 /* BinaryTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BinaryTest.swift; sourceTree = ""; }; - 1E9A62FC1C506EFC00E28AE1 /* BobExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BobExample.swift; sourceTree = ""; }; - 1E9A62FD1C506EFC00E28AE1 /* BobTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BobTest.swift; sourceTree = ""; }; + 1E9A62F41C506EFC00E28AE1 /* AnagramTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = AnagramTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A62F61C506EFC00E28AE1 /* AtbashExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = AtbashExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A62F71C506EFC00E28AE1 /* AtbashTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = AtbashTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A62F91C506EFC00E28AE1 /* BinaryExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = BinaryExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A62FA1C506EFC00E28AE1 /* BinaryTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = BinaryTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A62FC1C506EFC00E28AE1 /* BobExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = BobExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A62FD1C506EFC00E28AE1 /* BobTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = BobTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A62FF1C506EFC00E28AE1 /* ClockExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ClockExample.swift; sourceTree = ""; }; - 1E9A63001C506EFC00E28AE1 /* ClockTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ClockTest.swift; sourceTree = ""; }; - 1E9A63021C506EFC00E28AE1 /* CryptoSquareExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CryptoSquareExample.swift; sourceTree = ""; }; - 1E9A63031C506EFC00E28AE1 /* CryptoSquareTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CryptoSquareTest.swift; sourceTree = ""; }; - 1E9A63051C506EFC00E28AE1 /* CustomSetExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomSetExample.swift; sourceTree = ""; }; - 1E9A63061C506EFC00E28AE1 /* CustomSetTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CustomSetTest.swift; sourceTree = ""; }; + 1E9A63001C506EFC00E28AE1 /* ClockTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = ClockTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63021C506EFC00E28AE1 /* CryptoSquareExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = CryptoSquareExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63031C506EFC00E28AE1 /* CryptoSquareTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = CryptoSquareTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63051C506EFC00E28AE1 /* CustomSetExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = CustomSetExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63061C506EFC00E28AE1 /* CustomSetTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = CustomSetTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63081C506EFC00E28AE1 /* DifferenceOfSquaresExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DifferenceOfSquaresExample.swift; sourceTree = ""; }; - 1E9A63091C506EFC00E28AE1 /* DifferenceOfSquaresTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DifferenceOfSquaresTest.swift; sourceTree = ""; }; + 1E9A63091C506EFC00E28AE1 /* DifferenceOfSquaresTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = DifferenceOfSquaresTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A630B1C506EFC00E28AE1 /* EtlExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EtlExample.swift; sourceTree = ""; }; - 1E9A630C1C506EFC00E28AE1 /* EtlTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EtlTest.swift; sourceTree = ""; }; - 1E9A630E1C506EFC00E28AE1 /* GigasecondExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GigasecondExample.swift; sourceTree = ""; }; - 1E9A630F1C506EFC00E28AE1 /* GigasecondTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GigasecondTest.swift; sourceTree = ""; }; + 1E9A630C1C506EFC00E28AE1 /* EtlTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = EtlTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A630E1C506EFC00E28AE1 /* GigasecondExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = GigasecondExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A630F1C506EFC00E28AE1 /* GigasecondTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = GigasecondTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63111C506EFC00E28AE1 /* GradeSchoolExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GradeSchoolExample.swift; sourceTree = ""; }; - 1E9A63121C506EFC00E28AE1 /* GradeSchoolTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GradeSchoolTest.swift; sourceTree = ""; }; - 1E9A63141C506EFC00E28AE1 /* GrainsExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GrainsExample.swift; sourceTree = ""; }; - 1E9A63151C506EFC00E28AE1 /* GrainsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GrainsTest.swift; sourceTree = ""; }; + 1E9A63121C506EFC00E28AE1 /* GradeSchoolTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = GradeSchoolTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63141C506EFC00E28AE1 /* GrainsExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = GrainsExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63151C506EFC00E28AE1 /* GrainsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = GrainsTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63171C506EFC00E28AE1 /* HammingExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HammingExample.swift; sourceTree = ""; }; - 1E9A63181C506EFC00E28AE1 /* HammingTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HammingTest.swift; sourceTree = ""; }; + 1E9A63181C506EFC00E28AE1 /* HammingTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = HammingTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A631A1C506EFC00E28AE1 /* helloWorld.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = helloWorld.swift; sourceTree = ""; }; 1E9A631B1C506EFC00E28AE1 /* helloWorld.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = helloWorld.xcodeproj; sourceTree = ""; }; 1E9A631E1C506EFC00E28AE1 /* helloWorldExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = helloWorldExample.swift; sourceTree = ""; }; - 1E9A63201C506EFC00E28AE1 /* helloWorldTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = helloWorldTest.swift; sourceTree = ""; }; + 1E9A63201C506EFC00E28AE1 /* helloWorldTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = helloWorldTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63211C506EFC00E28AE1 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 1E9A63231C506EFC00E28AE1 /* KindergartenGardenExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KindergartenGardenExample.swift; sourceTree = ""; }; - 1E9A63241C506EFC00E28AE1 /* KindergartenGardenTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KindergartenGardenTest.swift; sourceTree = ""; }; + 1E9A63231C506EFC00E28AE1 /* KindergartenGardenExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = KindergartenGardenExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63241C506EFC00E28AE1 /* KindergartenGardenTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = KindergartenGardenTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63261C506EFC00E28AE1 /* LeapExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LeapExample.swift; sourceTree = ""; }; - 1E9A63271C506EFC00E28AE1 /* LeapTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LeapTest.swift; sourceTree = ""; }; - 1E9A63291C506EFC00E28AE1 /* LinkedListExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LinkedListExample.swift; sourceTree = ""; }; - 1E9A632A1C506EFC00E28AE1 /* LinkedListTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LinkedListTest.swift; sourceTree = ""; }; - 1E9A632C1C506EFC00E28AE1 /* LuhnExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LuhnExample.swift; sourceTree = ""; }; - 1E9A632D1C506EFC00E28AE1 /* LuhnTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LuhnTest.swift; sourceTree = ""; }; - 1E9A632F1C506EFC00E28AE1 /* MeetupExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MeetupExample.swift; sourceTree = ""; }; - 1E9A63301C506EFC00E28AE1 /* MeetupTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MeetupTest.swift; sourceTree = ""; }; - 1E9A63321C506EFC00E28AE1 /* NthPrimeExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NthPrimeExample.swift; sourceTree = ""; }; - 1E9A63331C506EFC00E28AE1 /* NthPrimeTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NthPrimeTest.swift; sourceTree = ""; }; + 1E9A63271C506EFC00E28AE1 /* LeapTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = LeapTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63291C506EFC00E28AE1 /* LinkedListExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = LinkedListExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A632A1C506EFC00E28AE1 /* LinkedListTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = LinkedListTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A632C1C506EFC00E28AE1 /* LuhnExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = LuhnExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A632D1C506EFC00E28AE1 /* LuhnTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = LuhnTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A632F1C506EFC00E28AE1 /* MeetupExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = MeetupExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63301C506EFC00E28AE1 /* MeetupTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = MeetupTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63321C506EFC00E28AE1 /* NthPrimeExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = NthPrimeExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63331C506EFC00E28AE1 /* NthPrimeTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = NthPrimeTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63351C506EFC00E28AE1 /* NucleotideCountExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NucleotideCountExample.swift; sourceTree = ""; }; - 1E9A63361C506EFC00E28AE1 /* NucleotideCountTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NucleotideCountTest.swift; sourceTree = ""; }; + 1E9A63361C506EFC00E28AE1 /* NucleotideCountTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = NucleotideCountTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63381C506EFC00E28AE1 /* OctalExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OctalExample.swift; sourceTree = ""; }; - 1E9A63391C506EFC00E28AE1 /* OctalTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OctalTest.swift; sourceTree = ""; }; + 1E9A63391C506EFC00E28AE1 /* OctalTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = OctalTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A633B1C506EFC00E28AE1 /* PerfectNumbersExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerfectNumbersExample.swift; sourceTree = ""; }; - 1E9A633C1C506EFC00E28AE1 /* PerfectNumbersTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerfectNumbersTest.swift; sourceTree = ""; }; + 1E9A633C1C506EFC00E28AE1 /* PerfectNumbersTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = PerfectNumbersTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A633E1C506EFC00E28AE1 /* PhoneNumberExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PhoneNumberExample.swift; sourceTree = ""; }; - 1E9A633F1C506EFC00E28AE1 /* PhoneNumberTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PhoneNumberTest.swift; sourceTree = ""; }; + 1E9A633F1C506EFC00E28AE1 /* PhoneNumberTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = PhoneNumberTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63411C506EFC00E28AE1 /* PigLatinExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PigLatinExample.swift; sourceTree = ""; }; - 1E9A63421C506EFC00E28AE1 /* PigLatinTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PigLatinTest.swift; sourceTree = ""; }; + 1E9A63421C506EFC00E28AE1 /* PigLatinTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = PigLatinTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63441C506EFC00E28AE1 /* PrimeFactorsExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrimeFactorsExample.swift; sourceTree = ""; }; - 1E9A63451C506EFC00E28AE1 /* PrimeFactorsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrimeFactorsTest.swift; sourceTree = ""; }; + 1E9A63451C506EFC00E28AE1 /* PrimeFactorsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = PrimeFactorsTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63471C506EFC00E28AE1 /* PythagoreanTripletExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PythagoreanTripletExample.swift; sourceTree = ""; }; - 1E9A63481C506EFC00E28AE1 /* PythagoreanTripletTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PythagoreanTripletTest.swift; sourceTree = ""; }; + 1E9A63481C506EFC00E28AE1 /* PythagoreanTripletTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = PythagoreanTripletTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A634A1C506EFC00E28AE1 /* QueenAttackExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueenAttackExample.swift; sourceTree = ""; }; - 1E9A634B1C506EFC00E28AE1 /* QueenAttackTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueenAttackTest.swift; sourceTree = ""; }; + 1E9A634B1C506EFC00E28AE1 /* QueenAttackTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = QueenAttackTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A634D1C506EFC00E28AE1 /* RaindropsExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RaindropsExample.swift; sourceTree = ""; }; - 1E9A634E1C506EFC00E28AE1 /* RaindropsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RaindropsTest.swift; sourceTree = ""; }; + 1E9A634E1C506EFC00E28AE1 /* RaindropsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = RaindropsTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63501C506EFC00E28AE1 /* RnaTranscriptionExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RnaTranscriptionExample.swift; sourceTree = ""; }; - 1E9A63511C506EFC00E28AE1 /* RnaTranscriptionTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RnaTranscriptionTest.swift; sourceTree = ""; }; + 1E9A63511C506EFC00E28AE1 /* RnaTranscriptionTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = RnaTranscriptionTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63531C506EFC00E28AE1 /* RobotNameExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RobotNameExample.swift; sourceTree = ""; }; - 1E9A63541C506EFC00E28AE1 /* RobotNameTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RobotNameTest.swift; sourceTree = ""; }; + 1E9A63541C506EFC00E28AE1 /* RobotNameTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = RobotNameTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63561C506EFC00E28AE1 /* RobotSimulatorExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RobotSimulatorExample.swift; sourceTree = ""; }; - 1E9A63571C506EFC00E28AE1 /* RobotSimulatorTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RobotSimulatorTest.swift; sourceTree = ""; }; + 1E9A63571C506EFC00E28AE1 /* RobotSimulatorTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = RobotSimulatorTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63591C506EFC00E28AE1 /* RomanNumeralsExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RomanNumeralsExample.swift; sourceTree = ""; }; - 1E9A635A1C506EFC00E28AE1 /* RomanNumeralsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RomanNumeralsTest.swift; sourceTree = ""; }; - 1E9A635C1C506EFC00E28AE1 /* ScrabbleScoreExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ScrabbleScoreExample.swift; sourceTree = ""; }; - 1E9A635D1C506EFC00E28AE1 /* ScrabbleScoreTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ScrabbleScoreTest.swift; sourceTree = ""; }; + 1E9A635A1C506EFC00E28AE1 /* RomanNumeralsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = RomanNumeralsTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A635C1C506EFC00E28AE1 /* ScrabbleScoreExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = ScrabbleScoreExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A635D1C506EFC00E28AE1 /* ScrabbleScoreTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = ScrabbleScoreTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A635F1C506EFC00E28AE1 /* SecretHandshakeExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SecretHandshakeExample.swift; sourceTree = ""; }; - 1E9A63601C506EFC00E28AE1 /* SecretHandshakeTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SecretHandshakeTest.swift; sourceTree = ""; }; - 1E9A63621C506EFC00E28AE1 /* SeriesExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SeriesExample.swift; sourceTree = ""; }; - 1E9A63631C506EFC00E28AE1 /* SeriesTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SeriesTest.swift; sourceTree = ""; }; - 1E9A63651C506EFC00E28AE1 /* SieveExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SieveExample.swift; sourceTree = ""; }; - 1E9A63661C506EFC00E28AE1 /* SieveTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SieveTest.swift; sourceTree = ""; }; - 1E9A63681C506EFC00E28AE1 /* SimpleCipherExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimpleCipherExample.swift; sourceTree = ""; }; - 1E9A63691C506EFC00E28AE1 /* SimpleCipherTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimpleCipherTest.swift; sourceTree = ""; }; - 1E9A636B1C506EFC00E28AE1 /* SimpleLinkedListExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimpleLinkedListExample.swift; sourceTree = ""; }; - 1E9A636C1C506EFC00E28AE1 /* SimpleLinkedListTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimpleLinkedListTest.swift; sourceTree = ""; }; - 1E9A636E1C506EFC00E28AE1 /* SpaceAgeExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SpaceAgeExample.swift; sourceTree = ""; }; - 1E9A636F1C506EFC00E28AE1 /* SpaceAgeTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SpaceAgeTest.swift; sourceTree = ""; }; + 1E9A63601C506EFC00E28AE1 /* SecretHandshakeTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SecretHandshakeTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63621C506EFC00E28AE1 /* SeriesExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SeriesExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63631C506EFC00E28AE1 /* SeriesTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SeriesTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63651C506EFC00E28AE1 /* SieveExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SieveExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63661C506EFC00E28AE1 /* SieveTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SieveTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63681C506EFC00E28AE1 /* SimpleCipherExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SimpleCipherExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63691C506EFC00E28AE1 /* SimpleCipherTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SimpleCipherTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A636B1C506EFC00E28AE1 /* SimpleLinkedListExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SimpleLinkedListExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A636C1C506EFC00E28AE1 /* SimpleLinkedListTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SimpleLinkedListTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A636E1C506EFC00E28AE1 /* SpaceAgeExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SpaceAgeExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A636F1C506EFC00E28AE1 /* SpaceAgeTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SpaceAgeTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63711C506EFC00E28AE1 /* StrainExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StrainExample.swift; sourceTree = ""; }; - 1E9A63721C506EFC00E28AE1 /* StrainTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StrainTest.swift; sourceTree = ""; }; + 1E9A63721C506EFC00E28AE1 /* StrainTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = StrainTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63741C506EFC00E28AE1 /* SumOfMultiplesExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SumOfMultiplesExample.swift; sourceTree = ""; }; - 1E9A63751C506EFC00E28AE1 /* SumOfMultiplesTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SumOfMultiplesTest.swift; sourceTree = ""; }; - 1E9A63771C506EFC00E28AE1 /* TournamentExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TournamentExample.swift; sourceTree = ""; }; - 1E9A63781C506EFC00E28AE1 /* TournamentTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TournamentTest.swift; sourceTree = ""; }; - 1E9A637A1C506EFC00E28AE1 /* TriangleExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TriangleExample.swift; sourceTree = ""; }; - 1E9A637B1C506EFC00E28AE1 /* TriangleTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TriangleTest.swift; sourceTree = ""; }; - 1E9A637D1C506EFC00E28AE1 /* TrinaryExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TrinaryExample.swift; sourceTree = ""; }; - 1E9A637E1C506EFC00E28AE1 /* TrinaryTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TrinaryTest.swift; sourceTree = ""; }; + 1E9A63751C506EFC00E28AE1 /* SumOfMultiplesTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = SumOfMultiplesTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63771C506EFC00E28AE1 /* TournamentExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = TournamentExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63781C506EFC00E28AE1 /* TournamentTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = TournamentTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A637A1C506EFC00E28AE1 /* TriangleExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = TriangleExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A637B1C506EFC00E28AE1 /* TriangleTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = TriangleTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A637D1C506EFC00E28AE1 /* TrinaryExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = TrinaryExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A637E1C506EFC00E28AE1 /* TrinaryTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = TrinaryTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63801C506EFC00E28AE1 /* TwelveDaysExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TwelveDaysExample.swift; sourceTree = ""; }; - 1E9A63811C506EFC00E28AE1 /* TwelveDaysTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TwelveDaysTest.swift; sourceTree = ""; }; + 1E9A63811C506EFC00E28AE1 /* TwelveDaysTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = TwelveDaysTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 1E9A63831C506EFC00E28AE1 /* WordCountExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WordCountExample.swift; sourceTree = ""; }; - 1E9A63841C506EFC00E28AE1 /* WordCountTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WordCountTest.swift; sourceTree = ""; }; - 1E9A63861C506EFC00E28AE1 /* WordyExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WordyExample.swift; sourceTree = ""; }; - 1E9A63871C506EFC00E28AE1 /* WordyTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WordyTest.swift; sourceTree = ""; }; - 1EAF95E01C90C587009DDCB6 /* DominoesTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DominoesTest.swift; sourceTree = ""; }; + 1E9A63841C506EFC00E28AE1 /* WordCountTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = WordCountTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63861C506EFC00E28AE1 /* WordyExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = WordyExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1E9A63871C506EFC00E28AE1 /* WordyTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = WordyTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + 1EAF95E01C90C587009DDCB6 /* DominoesTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; path = DominoesTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; 9D3155D21BA12FB1009A3991 /* xSwiftTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = xSwiftTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 9D3155D51BA12FB1009A3991 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; E908CD451C6AD05F005D081E /* FoodChainExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = FoodChainExample.swift; path = "food-chain/FoodChainExample.swift"; sourceTree = ""; }; - E908CD471C6AD076005D081E /* FoodChainTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = FoodChainTest.swift; path = "food-chain/FoodChainTest.swift"; sourceTree = ""; }; + E908CD471C6AD076005D081E /* FoodChainTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = FoodChainTest.swift; path = "food-chain/FoodChainTest.swift"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; E908CD531C6D7AD1005D081E /* PascalsTriangleExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PascalsTriangleExample.swift; path = "pascals-triangle/PascalsTriangleExample.swift"; sourceTree = ""; }; - E908CD551C6D7AF6005D081E /* PascalsTriangleTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PascalsTriangleTest.swift; path = "pascals-triangle/PascalsTriangleTest.swift"; sourceTree = ""; }; + E908CD551C6D7AF6005D081E /* PascalsTriangleTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = PascalsTriangleTest.swift; path = "pascals-triangle/PascalsTriangleTest.swift"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; E908CD5B1C6E7EC0005D081E /* SaddlePointsExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SaddlePointsExample.swift; path = "saddle-points/SaddlePointsExample.swift"; sourceTree = ""; }; - E908CD5D1C6E7EE1005D081E /* SaddlePointsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SaddlePointsTest.swift; path = "saddle-points/SaddlePointsTest.swift"; sourceTree = ""; }; - E90D61FD1C642EC600C266D3 /* OcrNumbersExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = OcrNumbersExample.swift; path = "ocr-numbers/OcrNumbersExample.swift"; sourceTree = ""; }; - E90D61FF1C642EFB00C266D3 /* OcrNumbersTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = OcrNumbersTest.swift; path = "ocr-numbers/OcrNumbersTest.swift"; sourceTree = ""; }; + E908CD5D1C6E7EE1005D081E /* SaddlePointsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = SaddlePointsTest.swift; path = "saddle-points/SaddlePointsTest.swift"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + E90D61FD1C642EC600C266D3 /* OcrNumbersExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = OcrNumbersExample.swift; path = "ocr-numbers/OcrNumbersExample.swift"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + E90D61FF1C642EFB00C266D3 /* OcrNumbersTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = OcrNumbersTest.swift; path = "ocr-numbers/OcrNumbersTest.swift"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; E90D62051C653AC000C266D3 /* PalindromeProductsExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PalindromeProductsExample.swift; path = "palindrome-products/PalindromeProductsExample.swift"; sourceTree = ""; }; - E90D62071C653ADC00C266D3 /* PalindromeProductsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = PalindromeProductsTest.swift; path = "palindrome-products/PalindromeProductsTest.swift"; sourceTree = ""; }; + E90D62071C653ADC00C266D3 /* PalindromeProductsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = PalindromeProductsTest.swift; path = "palindrome-products/PalindromeProductsTest.swift"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; E94BDECD1C510E68009318BB /* BinarySearchExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = BinarySearchExample.swift; path = "binary-search/BinarySearchExample.swift"; sourceTree = ""; }; - E94BDECE1C510E68009318BB /* BinarySearchTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = BinarySearchTest.swift; path = "binary-search/BinarySearchTest.swift"; sourceTree = ""; }; - E9AFA1461C593AF5006AD72D /* BinarySearchTreeExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = BinarySearchTreeExample.swift; path = "binary-search-tree/BinarySearchTreeExample.swift"; sourceTree = ""; }; - E9AFA1471C593AF5006AD72D /* BinarySearchTreeTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = BinarySearchTreeTest.swift; path = "binary-search-tree/BinarySearchTreeTest.swift"; sourceTree = ""; }; + E94BDECE1C510E68009318BB /* BinarySearchTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = BinarySearchTest.swift; path = "binary-search/BinarySearchTest.swift"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + E9AFA1461C593AF5006AD72D /* BinarySearchTreeExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = BinarySearchTreeExample.swift; path = "binary-search-tree/BinarySearchTreeExample.swift"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + E9AFA1471C593AF5006AD72D /* BinarySearchTreeTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = BinarySearchTreeTest.swift; path = "binary-search-tree/BinarySearchTreeTest.swift"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; E9AFA1501C5944D0006AD72D /* HexadecimalExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = HexadecimalExample.swift; path = hexadecimal/HexadecimalExample.swift; sourceTree = ""; }; - E9AFA1521C5945C9006AD72D /* HexadecimalTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = HexadecimalTest.swift; path = hexadecimal/HexadecimalTest.swift; sourceTree = ""; }; + E9AFA1521C5945C9006AD72D /* HexadecimalTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = HexadecimalTest.swift; path = hexadecimal/HexadecimalTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; E9AFA15F1C5BFC57006AD72D /* LargestSeriesProductExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = LargestSeriesProductExample.swift; path = "../largest-series-product/LargestSeriesProductExample.swift"; sourceTree = ""; }; - E9AFA16A1C5EF4DA006AD72D /* MatrixExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MatrixExample.swift; path = ../matrix/MatrixExample.swift; sourceTree = ""; }; - E9AFA16C1C5EF4EA006AD72D /* MatrixTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MatrixTest.swift; path = ../matrix/MatrixTest.swift; sourceTree = ""; }; + E9AFA16A1C5EF4DA006AD72D /* MatrixExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = MatrixExample.swift; path = ../matrix/MatrixExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + E9AFA16C1C5EF4EA006AD72D /* MatrixTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = MatrixTest.swift; path = ../matrix/MatrixTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; E9AFA1771C614D8D006AD72D /* HouseExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = HouseExample.swift; path = house/HouseExample.swift; sourceTree = ""; }; - E9AFA1791C614DA0006AD72D /* HouseTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = HouseTest.swift; path = house/HouseTest.swift; sourceTree = ""; }; - E9AFA17D1C61B162006AD72D /* LargestSeriesProductTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = LargestSeriesProductTest.swift; path = "../largest-series-product/LargestSeriesProductTest.swift"; sourceTree = ""; }; - E9AFA1841C624FB7006AD72D /* MinesweeperExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MinesweeperExample.swift; path = minesweeper/MinesweeperExample.swift; sourceTree = ""; }; - E9AFA1861C624FD5006AD72D /* MinesweeperTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MinesweeperTest.swift; path = minesweeper/MinesweeperTest.swift; sourceTree = ""; }; + E9AFA1791C614DA0006AD72D /* HouseTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = HouseTest.swift; path = house/HouseTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + E9AFA17D1C61B162006AD72D /* LargestSeriesProductTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = LargestSeriesProductTest.swift; path = "../largest-series-product/LargestSeriesProductTest.swift"; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + E9AFA1841C624FB7006AD72D /* MinesweeperExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = MinesweeperExample.swift; path = minesweeper/MinesweeperExample.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; + E9AFA1861C624FD5006AD72D /* MinesweeperTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; lineEnding = 0; name = MinesweeperTest.swift; path = minesweeper/MinesweeperTest.swift; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.swift; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -1023,6 +1023,7 @@ 9D3155CE1BA12FB1009A3991 /* Sources */, 9D3155CF1BA12FB1009A3991 /* Frameworks */, 9D3155D01BA12FB1009A3991 /* Resources */, + 1EB3CC5A1D307D8000F72FAC /* ShellScript */, ); buildRules = ( ); @@ -1046,6 +1047,7 @@ TargetAttributes = { 9D3155D11BA12FB1009A3991 = { CreatedOnToolsVersion = 6.4; + LastSwiftMigration = 0800; }; }; }; @@ -1093,6 +1095,22 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 1EB3CC5A1D307D8000F72FAC /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\ncd ..\nswiftlint\nelse\necho \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi"; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 9D3155CE1BA12FB1009A3991 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -1333,6 +1351,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.exercism.io.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -1348,6 +1367,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "com.exercism.io.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Release; };