From 0d984535bde0bad8e0e76857bdb504bc63bdcca9 Mon Sep 17 00:00:00 2001 From: Grant Timmerman Date: Wed, 4 Jun 2014 00:50:17 -0700 Subject: Added swift docs --- swift.html.markdown | 224 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 224 insertions(+) create mode 100644 swift.html.markdown (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown new file mode 100644 index 00000000..c7615a82 --- /dev/null +++ b/swift.html.markdown @@ -0,0 +1,224 @@ +--- +language: swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] +filename: learnswift.swift +--- + +Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta. + +See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. + +# Overview +- [Basics](#basics) +- [Arrays and Dictionaries](#array) +- [Control Flow](#control) +- [Functions](#func) +- [Closures](#closures) +- [Classes](#classes) +- [Enums](#enums) +- [Other](#other) +- [Links](#links) + +## Basics + +```js +println("Hello, world") +var myVariable = 42 +let myConstant = 3.1415926 +let explicitDouble: Double = 70 +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(myConstant)" // String interpolation +var optionalString: String? = "optional" // Can be nil +optionalString = nil +``` + +## Arrays and Dictionaries + +```js +// Array +var shoppingList = ["catfish", "water", "lemons"] +shoppingList[1] = "bottle of water" +let emptyArray = String[]() + +// Dictionary +var occupations = [ + "Malcolm": "Captain", + "kaylee": "Mechanic" +] +occupations["Jayne"] = "Public Relations" +let emptyDictionary = Dictionary() +``` + +## Control Flow + +```js +// for loop (array) +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + println("One!") + } else { + println("Not one!") + } +} + +// for loop (dictionary) +for (key, value) in dict { + println("\(key): \(value)") +} + +// for loop (range) +for i in -1...1 { // [-1, 0, 1] + println(i) +} +// use .. to exclude the last number + +// while loop +var i = 1 +while i < 1000 { + i *= 2 +} + +// do-while loop +do { + println("hello") +} while 1 == 2 + +// Switch +let vegetable = "red pepper" +switch vegetable { +case "celery": + let vegetableComment = "Add some raisins and make ants on a log." +case "cucumber", "watercress": + let vegetableComment = "That would make a good tea sandwich." +case let x where x.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(x)?" +default: // required (in order to cover all possible input) + let vegetableComment = "Everything tastes good in soup." +} +``` + +## Functions + +Functions are a first-class type, meaning they can be nested in functions and can be passed around + +```js +// Function +func greet(name: String, day: String) -> String { + return "Hello \(name), today is \(day)." +} +greet("Bob", "Tuesday") + +// Function that returns multiple items in a tuple +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} + +// Args +func setup(numbers: Int...) {} + +// Passing and returning functions +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) +``` + +## Closures + +Functions are special case closures ({}) + +```js +// Closure example. +// `->` separates the arguments and return type +// `in` separates the closure header from the closure body +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result + }) + +// When the type is known, like above, we can do this +var numbers = [1, 2, 6] +numbers = numbers.map({ number in 3 * number }) +print(numbers) // [3, 6, 18] +``` + +## Classes + +All methods and properties of a class are public. If you just need to store data +in a structured object, you should use a `struct` + +```js +// A simple class `Square` extends `Shape +class Rect: Shape { + var sideLength: Int = 1 + + // Custom getter and setter property + var perimeter: Int { + get { + return 4 * sideLength + } + set { + sideLength = newValue / 4 + } + } + + init(sideLength: Int) { + super.init() + self.sideLength = sideLength + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} +var mySquare = new Square(sideLength: 5) +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// If you don't need a custom getter and setter, but still want to run code +// before an after getting or setting a property, you can use `willSet` and `didSet` +``` + +## Enums + +Enums can optionally be of a specific type or on their own. They can contain methods like classes. + +```js +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} +``` + +## Other + +- **`protocol`**: Similar to Java interfaces. +- **`extension`s**: Add extra functionality to an already created type +- **Generics**: Similar to Java. Use the `where` keyword to specify the requirements of the generics. + +## Links + +- [Homepage](https://developer.apple.com/swift/) +- [Guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) +- [Book](https://itunes.apple.com/us/book/the-swift-programming-language/id881256329?mt=11) -- cgit v1.2.3 From 76f4c1b3b6d99d05197224dfec905a46dbd80713 Mon Sep 17 00:00:00 2001 From: Grant Timmerman Date: Wed, 4 Jun 2014 13:22:01 -0700 Subject: Formatted the document according to the guidelines --- swift.html.markdown | 94 ++++++++++++++++++++++++++--------------------------- 1 file changed, 47 insertions(+), 47 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index c7615a82..6ab0cc20 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -9,20 +9,11 @@ Swift is a programming language for iOS and OS X development created by Apple. D See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. -# Overview -- [Basics](#basics) -- [Arrays and Dictionaries](#array) -- [Control Flow](#control) -- [Functions](#func) -- [Closures](#closures) -- [Classes](#classes) -- [Enums](#enums) -- [Other](#other) -- [Links](#links) - -## Basics - ```js +// +// Basics +// + println("Hello, world") var myVariable = 42 let myConstant = 3.1415926 @@ -31,11 +22,12 @@ let label = "some text " + String(myVariable) // Casting let piText = "Pi = \(myConstant)" // String interpolation var optionalString: String? = "optional" // Can be nil optionalString = nil -``` -## Arrays and Dictionaries -```js +// +// Arrays and Dictionaries +// + // Array var shoppingList = ["catfish", "water", "lemons"] shoppingList[1] = "bottle of water" @@ -48,11 +40,12 @@ var occupations = [ ] occupations["Jayne"] = "Public Relations" let emptyDictionary = Dictionary() -``` -## Control Flow -```js +// +// Control Flow +// + // for loop (array) let myArray = [1, 1, 2, 3, 5] for value in myArray { @@ -97,13 +90,15 @@ case let x where x.hasSuffix("pepper"): default: // required (in order to cover all possible input) let vegetableComment = "Everything tastes good in soup." } -``` -## Functions -Functions are a first-class type, meaning they can be nested in functions and can be passed around +// +// Functions +// + +// Functions are a first-class type, meaning they can be nested +// in functions and can be passed around -```js // Function func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." @@ -127,13 +122,14 @@ func makeIncrementer() -> (Int -> Int) { } var increment = makeIncrementer() increment(7) -``` -## Closures -Functions are special case closures ({}) +// +// Closures +// + +// Functions are special case closures ({}) -```js // Closure example. // `->` separates the arguments and return type // `in` separates the closure header from the closure body @@ -147,14 +143,16 @@ numbers.map({ var numbers = [1, 2, 6] numbers = numbers.map({ number in 3 * number }) print(numbers) // [3, 6, 18] -``` -## Classes -All methods and properties of a class are public. If you just need to store data -in a structured object, you should use a `struct` +// +// Classes +// + +// All methods and properties of a class are public. +// If you just need to store data in a +// structured object, you should use a `struct` -```js // A simple class `Square` extends `Shape class Rect: Shape { var sideLength: Int = 1 @@ -189,15 +187,18 @@ print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 -// If you don't need a custom getter and setter, but still want to run code -// before an after getting or setting a property, you can use `willSet` and `didSet` -``` +// If you don't need a custom getter and setter, +// but still want to run code before an after getting or setting +// a property, you can use `willSet` and `didSet` -## Enums -Enums can optionally be of a specific type or on their own. They can contain methods like classes. +// +// Enums +// + +// Enums can optionally be of a specific type or on their own. +// They can contain methods like classes. -```js enum Suit { case Spades, Hearts, Diamonds, Clubs func getIcon() -> String { @@ -209,16 +210,15 @@ enum Suit { } } } -``` -## Other -- **`protocol`**: Similar to Java interfaces. -- **`extension`s**: Add extra functionality to an already created type -- **Generics**: Similar to Java. Use the `where` keyword to specify the requirements of the generics. +// +// Other +// -## Links +// `protocol`: Similar to Java interfaces. +// `extension`s: Add extra functionality to an already created type +// Generics: Similar to Java. Use the `where` keyword to specify the +// requirements of the generics. -- [Homepage](https://developer.apple.com/swift/) -- [Guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) -- [Book](https://itunes.apple.com/us/book/the-swift-programming-language/id881256329?mt=11) +``` \ No newline at end of file -- cgit v1.2.3 From e07f88cb4db7e1eac0668707d4c06ab68a967253 Mon Sep 17 00:00:00 2001 From: Xavier Yao Date: Thu, 5 Jun 2014 22:49:42 +0800 Subject: Tiny symbol missing fixed. --- swift.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 6ab0cc20..f24b1592 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -153,7 +153,7 @@ print(numbers) // [3, 6, 18] // If you just need to store data in a // structured object, you should use a `struct` -// A simple class `Square` extends `Shape +// A simple class `Square` extends `Shape` class Rect: Shape { var sideLength: Int = 1 @@ -188,7 +188,7 @@ mySquare.shrink() print(mySquare.sideLength) // 4 // If you don't need a custom getter and setter, -// but still want to run code before an after getting or setting +// but still want to run code before and after getting or setting // a property, you can use `willSet` and `didSet` -- cgit v1.2.3 From ba855b16643661fef54842c5eb2d7ec93e29c4f9 Mon Sep 17 00:00:00 2001 From: Umberto Raimondi Date: Wed, 16 Jul 2014 12:20:57 +0200 Subject: Update swift to beta3 Updated to beta3, new array declaration style,".." and a few other modifications. --- swift.html.markdown | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index f24b1592..a47b085a 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -31,7 +31,7 @@ optionalString = nil // Array var shoppingList = ["catfish", "water", "lemons"] shoppingList[1] = "bottle of water" -let emptyArray = String[]() +let emptyArray = [String]() // Dictionary var occupations = [ @@ -65,7 +65,7 @@ for (key, value) in dict { for i in -1...1 { // [-1, 0, 1] println(i) } -// use .. to exclude the last number +// use ..< to exclude the last number // while loop var i = 1 @@ -127,6 +127,7 @@ increment(7) // // Closures // +var numbers = [1, 2, 6] // Functions are special case closures ({}) @@ -140,8 +141,10 @@ numbers.map({ }) // When the type is known, like above, we can do this -var numbers = [1, 2, 6] numbers = numbers.map({ number in 3 * number }) +//Or even this +//numbers = numbers.map({ $0 * 3 }) + print(numbers) // [3, 6, 18] @@ -221,4 +224,4 @@ enum Suit { // Generics: Similar to Java. Use the `where` keyword to specify the // requirements of the generics. -``` \ No newline at end of file +``` -- cgit v1.2.3 From 328a4f1babe167e94858b92faaa9caa19aa8aade Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sat, 23 Aug 2014 22:48:10 -0500 Subject: - add more examples; update examples - now runs in the Xcode 6 b6 playground - add MARK sections --- swift.html.markdown | 206 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 135 insertions(+), 71 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index a47b085a..5ba160b8 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -2,6 +2,7 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] filename: learnswift.swift --- @@ -11,21 +12,34 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre ```js // -// Basics +// MARK: Basics // println("Hello, world") + var myVariable = 42 +//let fƒ∆ = "value" // unicode in variable names let myConstant = 3.1415926 +let convenience = "keyword" // contextual variable name +let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon +let `class` = "keyword" // backticks allow keywords to be used as variable names let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 let label = "some text " + String(myVariable) // Casting let piText = "Pi = \(myConstant)" // String interpolation var optionalString: String? = "optional" // Can be nil optionalString = nil +/* +Comment here + /* + Nested comment here + */ +*/ // -// Arrays and Dictionaries +// MARK: Collections // // Array @@ -35,65 +49,66 @@ let emptyArray = [String]() // Dictionary var occupations = [ - "Malcolm": "Captain", - "kaylee": "Mechanic" + "Malcolm": "Captain", + "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" let emptyDictionary = Dictionary() // -// Control Flow +// MARK: Control Flow // // for loop (array) let myArray = [1, 1, 2, 3, 5] for value in myArray { - if value == 1 { - println("One!") - } else { - println("Not one!") - } + if value == 1 { + println("One!") + } else { + println("Not one!") + } } // for loop (dictionary) +var dict = ["one": 1, "two": 2] for (key, value) in dict { - println("\(key): \(value)") + println("\(key): \(value)") } // for loop (range) for i in -1...1 { // [-1, 0, 1] - println(i) + println(i) } // use ..< to exclude the last number // while loop var i = 1 while i < 1000 { - i *= 2 + i *= 2 } // do-while loop do { - println("hello") + println("hello") } while 1 == 2 // Switch let vegetable = "red pepper" switch vegetable { case "celery": - let vegetableComment = "Add some raisins and make ants on a log." + let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": - let vegetableComment = "That would make a good tea sandwich." + let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): - let vegetableComment = "Is it a spicy \(x)?" + let vegetableComment = "Is it a spicy \(x)?" default: // required (in order to cover all possible input) - let vegetableComment = "Everything tastes good in soup." + let vegetableComment = "Everything tastes good in soup." } // -// Functions +// MARK: Functions // // Functions are a first-class type, meaning they can be nested @@ -101,31 +116,31 @@ default: // required (in order to cover all possible input) // Function func greet(name: String, day: String) -> String { - return "Hello \(name), today is \(day)." + return "Hello \(name), today is \(day)." } greet("Bob", "Tuesday") // Function that returns multiple items in a tuple func getGasPrices() -> (Double, Double, Double) { - return (3.59, 3.69, 3.79) + return (3.59, 3.69, 3.79) } -// Args +// Variadic Args func setup(numbers: Int...) {} // Passing and returning functions func makeIncrementer() -> (Int -> Int) { - func addOne(number: Int) -> Int { - return 1 + number - } - return addOne + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne } var increment = makeIncrementer() increment(7) // -// Closures +// MARK: Closures // var numbers = [1, 2, 6] @@ -135,93 +150,142 @@ var numbers = [1, 2, 6] // `->` separates the arguments and return type // `in` separates the closure header from the closure body numbers.map({ - (number: Int) -> Int in - let result = 3 * number - return result - }) + (number: Int) -> Int in + let result = 3 * number + return result +}) // When the type is known, like above, we can do this numbers = numbers.map({ number in 3 * number }) -//Or even this +// Or even this //numbers = numbers.map({ $0 * 3 }) print(numbers) // [3, 6, 18] +// Trailing closure +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Super shorthand, since the < operator infers the types + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] // -// Classes +// MARK: Classes // +class Shape { + func getArea() -> Int { + return 0; + } +} + // All methods and properties of a class are public. // If you just need to store data in a // structured object, you should use a `struct` // A simple class `Square` extends `Shape` class Rect: Shape { - var sideLength: Int = 1 - - // Custom getter and setter property - var perimeter: Int { - get { - return 4 * sideLength + var sideLength: Int = 1 + + // Custom getter and setter property + var perimeter: Int { + get { + return 4 * sideLength + } + set { + sideLength = newValue / 4 + } } - set { - sideLength = newValue / 4 + + // If you don't need a custom getter and setter, + // but still want to run code before and after getting or setting + // a property, you can use `willSet` and `didSet` + var identifier: String = "defaultID" { + willSet(someIdentifier) { + print(someIdentifier) + } } - } - - init(sideLength: Int) { - super.init() - self.sideLength = sideLength - } - - func shrink() { - if sideLength > 0 { - --sideLength + + init(sideLength: Int) { + super.init() + self.sideLength = sideLength + } + + func shrink() { + if sideLength > 0 { + --sideLength + } } - } + + override func getArea() -> Int { + return sideLength * sideLength + } +} - override func getArea() -> Int { - return sideLength * sideLength - } +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } } -var mySquare = new Square(sideLength: 5) + +var mySquare = Square() print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 -// If you don't need a custom getter and setter, -// but still want to run code before and after getting or setting -// a property, you can use `willSet` and `didSet` - // -// Enums +// MARK: Enums // // Enums can optionally be of a specific type or on their own. // They can contain methods like classes. enum Suit { - case Spades, Hearts, Diamonds, Clubs - func getIcon() -> String { - switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } } - } } // -// Other +// MARK: Other // // `protocol`: Similar to Java interfaces. -// `extension`s: Add extra functionality to an already created type +protocol ShapeGenerator { + func buildShape() -> Shape +} + +// `extension`s: Add extra functionality to an already existing type +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +println("Square: \(mySquare)") + // Generics: Similar to Java. Use the `where` keyword to specify the // requirements of the generics. +func findIndex(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} + ``` -- cgit v1.2.3 From 6b34ef65a3aea7af638145be83c1d3699caa353b Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 00:48:54 -0500 Subject: - more examples - add custom operator example --- swift.html.markdown | 54 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 4 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 5ba160b8..6ce60cf5 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -26,9 +26,9 @@ let `class` = "keyword" // backticks allow keywords to be used as variable names let explicitDouble: Double = 70 let intValue = 0007 // 7 let largeIntValue = 77_000 // 77000 -let label = "some text " + String(myVariable) // Casting -let piText = "Pi = \(myConstant)" // String interpolation -var optionalString: String? = "optional" // Can be nil +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(myConstant), Pi 2 = \(myConstant * 2)" // String interpolation +var optionalString: String? = "optional" // Can be nil optionalString = nil /* @@ -114,7 +114,17 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function +// Function with Swift docs +/** + A greet operation + + - A bullet in docs + - Another bullet in the docs + + :param: name A name + :param: day A day + :returns: A string containing the name and day value. +*/ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } @@ -237,6 +247,11 @@ print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 +// compare instances, not the same as == which compares objects (equal to) +if mySquare === mySquare { + println("Yep its mySquare") +} + // // MARK: Enums @@ -276,6 +291,20 @@ extension Square: Printable { println("Square: \(mySquare)") +// You can also extend built-in types +extension Int { + var customProperty: String { + return "This is \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +println(7.customProperty) // "This is 7" +println(14.multiplyBy(2)) // 42 + // Generics: Similar to Java. Use the `where` keyword to specify the // requirements of the generics. @@ -288,4 +317,21 @@ func findIndex(array: [T], valueToFind: T) -> Int? { return nil } + +// Operators: +// Custom operators can start with the characters: +// / = - + * % < > ! & | ^ . ~ +// or +// Unicode math, symbol, arrow, dingbat, and line/box drawing characters. +prefix operator !!! {} + +// An operator that triples the side length when used +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +let bigSquare = !!!mySquare +println(bigSquare.sideLength) + ``` -- cgit v1.2.3 From 2a5a4ebf64593009002053514deb057f37d7b693 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 14:37:09 -0500 Subject: - add landmark notes --- swift.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 6ce60cf5..600eedcf 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -15,6 +15,11 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre // MARK: Basics // +// Xcode supports landmarks to annotate your code and lists them in the jump bar +// MARK: Section mark +// TODO: Do something soon +// FIXME Fix this code + println("Hello, world") var myVariable = 42 @@ -114,7 +119,7 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function with Swift docs +// Function with Swift function docs /** A greet operation -- cgit v1.2.3 From b50d4443cdca87e3342e2364c9e6afd2d7fce7d2 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sun, 24 Aug 2014 18:33:16 -0500 Subject: - add more examples; add book link - add link to official Swift book from Apple - add examples of access control and structures - update protocols --- swift.html.markdown | 95 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 81 insertions(+), 14 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 600eedcf..f8fa31fe 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -8,6 +8,8 @@ filename: learnswift.swift Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta. +The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. + See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. ```js @@ -23,7 +25,7 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre println("Hello, world") var myVariable = 42 -//let fƒ∆ = "value" // unicode in variable names +let øπΩ = "value" // unicode variable names let myConstant = 3.1415926 let convenience = "keyword" // contextual variable name let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon @@ -39,7 +41,7 @@ optionalString = nil /* Comment here /* - Nested comment here + Nested comments are also supported */ */ @@ -119,7 +121,7 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function with Swift function docs +// Function with Swift header docs (format as reStructedText) /** A greet operation @@ -188,12 +190,34 @@ numbers = sorted(numbers, < ) print(numbers) // [3, 6, 18] +// +// MARK: Structures +// + +// Structures and classes have very similar capabilites +struct NamesTable { + let names: [String] + + // Custom subscript + subscript(index: Int) -> String { + return names[index] + } +} + +// Structures have an auto-generated (implicit) designated initializer +let namesTable = NamesTable(names: ["Me", "Them"]) +//let name = namesTable[2] +//println("Name is \(name)") // Name is Them + // // MARK: Classes // -class Shape { - func getArea() -> Int { +// Classes, structures and its members have three levels of access control +// They are: internal (default), public, private + +public class Shape { + public func getArea() -> Int { return 0; } } @@ -203,23 +227,29 @@ class Shape { // structured object, you should use a `struct` // A simple class `Square` extends `Shape` -class Rect: Shape { +internal class Rect: Shape { var sideLength: Int = 1 // Custom getter and setter property - var perimeter: Int { + private var perimeter: Int { get { return 4 * sideLength } set { + // `newValue` is an implicit variable available to setters sideLength = newValue / 4 } } + + // Lazily load a property + // subShape remains nil (uninitialized) until getter called + lazy var subShape = Rect(sideLength: 4) // If you don't need a custom getter and setter, // but still want to run code before and after getting or setting // a property, you can use `willSet` and `didSet` var identifier: String = "defaultID" { + // the `willSet` arg will be the variable name for the new value willSet(someIdentifier) { print(someIdentifier) } @@ -254,7 +284,7 @@ print(mySquare.sideLength) // 4 // compare instances, not the same as == which compares objects (equal to) if mySquare === mySquare { - println("Yep its mySquare") + println("Yep, it's mySquare") } @@ -279,15 +309,47 @@ enum Suit { // -// MARK: Other +// MARK: Protocols // -// `protocol`: Similar to Java interfaces. +// `protocol`s can require that conforming types have specific +// instance properties, instance methods, type methods, +// operators, and subscripts. + protocol ShapeGenerator { + var enabled: Bool { get set } func buildShape() -> Shape } +/* +// Protocols declared with @objc allow optional functions, +// which allow you to check for conformance +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + if let allow = self.delegate?.canReshape?() { + // test for delegate then for method + self.delegate?.reshaped?() + } + } +} +*/ + +// +// MARK: Other +// + // `extension`s: Add extra functionality to an already existing type + +// Square now "conforms" to the `Printable` protocol extension Square: Printable { var description: String { return "Area: \(self.getArea()) - ID: \(self.identifier)" @@ -321,7 +383,8 @@ func findIndex(array: [T], valueToFind: T) -> Int? { } return nil } - +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +println(foundAtIndex == 2) // true // Operators: // Custom operators can start with the characters: @@ -330,13 +393,17 @@ func findIndex(array: [T], valueToFind: T) -> Int? { // Unicode math, symbol, arrow, dingbat, and line/box drawing characters. prefix operator !!! {} -// An operator that triples the side length when used +// A prefix operator that triples the side length when used prefix func !!! (inout shape: Square) -> Square { shape.sideLength *= 3 return shape } -let bigSquare = !!!mySquare -println(bigSquare.sideLength) +// current value +println(mySquare.sideLength) // 4 + +// change side length using custom !!! operator, increases size by 3 +!!!mySquare +println(mySquare.sideLength) // 12 ``` -- cgit v1.2.3 From 54bd312f8de72d4ca109fb12351b44203a482d23 Mon Sep 17 00:00:00 2001 From: "Janne R." Date: Tue, 26 Aug 2014 20:48:35 +0300 Subject: Use preferred shorthand syntax for dictionary type --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index a47b085a..a0ea8519 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -39,7 +39,7 @@ var occupations = [ "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" -let emptyDictionary = Dictionary() +let emptyDictionary = [String: Float]() // -- cgit v1.2.3 From c9400c2a7d5262651884fffecda83ace1bfc4d97 Mon Sep 17 00:00:00 2001 From: Assaf Gelber Date: Thu, 28 Aug 2014 14:00:25 +0300 Subject: Change swift class name to Square --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index a0ea8519..6d98b067 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -157,7 +157,7 @@ print(numbers) // [3, 6, 18] // structured object, you should use a `struct` // A simple class `Square` extends `Shape` -class Rect: Shape { +class Square: Shape { var sideLength: Int = 1 // Custom getter and setter property -- cgit v1.2.3 From eab554a7a7f2869ff7dac9f54acce9a7ed55cfa4 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 8 Sep 2014 13:08:28 +0200 Subject: Review docs for added rouge lexers and update those with new highlighters --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index e7f2f9a2..77047355 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -12,7 +12,7 @@ The official [Swift Programming Language](https://itunes.apple.com/us/book/swift See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. -```js +```swift // // MARK: Basics // -- cgit v1.2.3 From 923a8ed99b1648cc2ece83660ed263492c332afe Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sat, 4 Oct 2014 12:08:23 -0500 Subject: - mo betta examples - add `inout` example - better `optional` example - Playground issue has been resolved, uncommented `protocol` example --- swift.html.markdown | 81 ++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 59 insertions(+), 22 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 77047355..ffe6cac2 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -13,6 +13,9 @@ The official [Swift Programming Language](https://itunes.apple.com/us/book/swift See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. ```swift +// import a module +import UIKit + // // MARK: Basics // @@ -26,7 +29,7 @@ println("Hello, world") var myVariable = 42 let øπΩ = "value" // unicode variable names -let myConstant = 3.1415926 +let π = 3.1415926 let convenience = "keyword" // contextual variable name let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon let `class` = "keyword" // backticks allow keywords to be used as variable names @@ -34,9 +37,24 @@ let explicitDouble: Double = 70 let intValue = 0007 // 7 let largeIntValue = 77_000 // 77000 let label = "some text " + String(myVariable) // Casting -let piText = "Pi = \(myConstant), Pi 2 = \(myConstant * 2)" // String interpolation -var optionalString: String? = "optional" // Can be nil -optionalString = nil +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation +var someOptionalString: String? = "optional" // Can be nil + +if someOptionalString != nil { + // I am not nil + if someOptionalString!.hasPrefix("opt") { + println("has the prefix") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +if let someStringConstant = someOptionalString { + // has Some value +} + +// AnyObject == id /* Comment here @@ -84,9 +102,10 @@ for (key, value) in dict { } // for loop (range) -for i in -1...1 { // [-1, 0, 1] +for i in -1...shoppingList.count { println(i) } +shoppingList[1...2] = ["steak", "peacons"] // use ..< to exclude the last number // while loop @@ -123,14 +142,14 @@ default: // required (in order to cover all possible input) // Function with Swift header docs (format as reStructedText) /** - A greet operation +A greet operation - - A bullet in docs - - Another bullet in the docs +- A bullet in docs +- Another bullet in the docs - :param: name A name - :param: day A day - :returns: A string containing the name and day value. +:param: name A name +:param: day A day +:returns: A string containing the name and day value. */ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." @@ -141,9 +160,16 @@ greet("Bob", "Tuesday") func getGasPrices() -> (Double, Double, Double) { return (3.59, 3.69, 3.79) } +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +println("Gas price: \(price)") // Variadic Args -func setup(numbers: Int...) {} +func setup(numbers: Int...) { + // its an array + let number = numbers[0] + let argCount = numbers.count +} // Passing and returning functions func makeIncrementer() -> (Int -> Int) { @@ -155,6 +181,17 @@ func makeIncrementer() -> (Int -> Int) { var increment = makeIncrementer() increment(7) +// pass by ref +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +println(someIntB) // 7 + // // MARK: Closures @@ -197,7 +234,7 @@ print(numbers) // [3, 6, 18] // Structures and classes have very similar capabilites struct NamesTable { let names: [String] - + // Custom subscript subscript(index: Int) -> String { return names[index] @@ -239,7 +276,7 @@ internal class Rect: Shape { sideLength = newValue / 4 } } - + // Lazily load a property // subShape remains nil (uninitialized) until getter called lazy var subShape = Rect(sideLength: 4) @@ -255,8 +292,9 @@ internal class Rect: Shape { } init(sideLength: Int) { - super.init() self.sideLength = sideLength + // always super.init last when init custom properties + super.init() } func shrink() { @@ -313,7 +351,7 @@ enum Suit { // // `protocol`s can require that conforming types have specific -// instance properties, instance methods, type methods, +// instance properties, instance methods, type methods, // operators, and subscripts. protocol ShapeGenerator { @@ -321,7 +359,6 @@ protocol ShapeGenerator { func buildShape() -> Shape } -/* // Protocols declared with @objc allow optional functions, // which allow you to check for conformance @objc protocol TransformShape { @@ -331,17 +368,17 @@ protocol ShapeGenerator { class MyShape: Rect { var delegate: TransformShape? - + func grow() { sideLength += 2 - + if let allow = self.delegate?.canReshape?() { // test for delegate then for method self.delegate?.reshaped?() } } } -*/ + // // MARK: Other @@ -363,7 +400,7 @@ extension Int { var customProperty: String { return "This is \(self)" } - + func multiplyBy(num: Int) -> Int { return num * self } @@ -372,7 +409,7 @@ extension Int { println(7.customProperty) // "This is 7" println(14.multiplyBy(2)) // 42 -// Generics: Similar to Java. Use the `where` keyword to specify the +// Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. func findIndex(array: [T], valueToFind: T) -> Int? { -- cgit v1.2.3 From 679d7098f2fe663b62e7a7e328369b760f94195c Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Fri, 17 Oct 2014 21:22:28 -0500 Subject: - update examples - further explain Optional types - add build config example - explain array/dictionary mutability - expand tuple example --- swift.html.markdown | 56 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 4 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index ffe6cac2..005e511c 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -27,6 +27,9 @@ import UIKit println("Hello, world") +// variables (var) value can change after being set +// constants (let) value can NOT be changed after being set + var myVariable = 42 let øπΩ = "value" // unicode variable names let π = 3.1415926 @@ -38,7 +41,29 @@ let intValue = 0007 // 7 let largeIntValue = 77_000 // 77000 let label = "some text " + String(myVariable) // Casting let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation + +// Build Specific values +// uses -D build configuration +#if false + println("Not printed") + let buildValue = 3 +#else + let buildValue = 7 +#endif +println("Build value: \(buildValue)") // Build value: 7 + +/* + Optionals are a Swift language feature that allows you to store a `Some` or + `None` value. + + Because Swift requires every property to have a value, even nil must be + explicitly stored as an Optional value. + + Optional is an enum. +*/ var someOptionalString: String? = "optional" // Can be nil +// same as above, but ? is a postfix operator (syntax candy) +var someOptionalString2: Optional = "optional" if someOptionalString != nil { // I am not nil @@ -50,11 +75,23 @@ if someOptionalString != nil { } someOptionalString = nil -if let someStringConstant = someOptionalString { - // has Some value +// implicitly unwrapped optional +var unwrappedString: String! = "Value is expected." +// same as above, but ! is a postfix operator (more syntax candy) +var unwrappedString2: ImplicitlyUnwrappedOptional = "Value is expected." + +if let someOptionalStringConstant = someOptionalString { + // has `Some` value, non-nil + if !someOptionalStringConstant.hasPrefix("ok") { + // does not have the prefix + } } +// Swift has support for storing a value of any type. // AnyObject == id +// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Changed value to a string, not good practice, but possible." /* Comment here @@ -67,10 +104,17 @@ Comment here // MARK: Collections // +/* + Array and Dictionary types are structs. So `let` and `var` also indicate + that they are mutable (var) or immutable (let) when declaring these types. +*/ + // Array var shoppingList = ["catfish", "water", "lemons"] shoppingList[1] = "bottle of water" -let emptyArray = [String]() +let emptyArray = [String]() // immutable +var emptyMutableArray = [String]() // mutable + // Dictionary var occupations = [ @@ -78,7 +122,8 @@ var occupations = [ "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" -let emptyDictionary = [String: Float]() +let emptyDictionary = [String: Float]() // immutable +var emptyMutableDictionary = [String: Float]() // mutable // @@ -162,6 +207,9 @@ func getGasPrices() -> (Double, Double, Double) { } let pricesTuple = getGasPrices() let price = pricesTuple.2 // 3.79 +// Ignore Tuple (or other) values by using _ (underscore) +let (_, price1, _) = pricesTuple // price1 == 3.69 +println(price1 == pricesTuple.1) // true println("Gas price: \(price)") // Variadic Args -- cgit v1.2.3 From 3a7e00127fef6f72b36f9b86083928623d3a1ab8 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Sat, 13 Dec 2014 20:01:08 -0600 Subject: - update examples, update comments - add another Switch example - add more complex func example - fix playground error - add another casting example --- swift.html.markdown | 69 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 47 insertions(+), 22 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 005e511c..0d1d2df4 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -6,7 +6,7 @@ contributors: filename: learnswift.swift --- -Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta. +Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+. The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. @@ -23,7 +23,7 @@ import UIKit // Xcode supports landmarks to annotate your code and lists them in the jump bar // MARK: Section mark // TODO: Do something soon -// FIXME Fix this code +// FIXME: Fix this code println("Hello, world") @@ -55,8 +55,8 @@ println("Build value: \(buildValue)") // Build value: 7 /* Optionals are a Swift language feature that allows you to store a `Some` or `None` value. - - Because Swift requires every property to have a value, even nil must be + + Because Swift requires every property to have a value, even nil must be explicitly stored as an Optional value. Optional is an enum. @@ -94,7 +94,8 @@ var anyObjectVar: AnyObject = 7 anyObjectVar = "Changed value to a string, not good practice, but possible." /* -Comment here + Comment here + /* Nested comments are also supported */ @@ -112,8 +113,9 @@ Comment here // Array var shoppingList = ["catfish", "water", "lemons"] shoppingList[1] = "bottle of water" -let emptyArray = [String]() // immutable -var emptyMutableArray = [String]() // mutable +let emptyArray = [String]() // let == immutable +let emptyArray2 = Array() // same as above +var emptyMutableArray = [String]() // var == mutable // Dictionary @@ -122,8 +124,9 @@ var occupations = [ "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" -let emptyDictionary = [String: Float]() // immutable -var emptyMutableDictionary = [String: Float]() // mutable +let emptyDictionary = [String: Float]() // let == immutable +let emptyDictionary2 = Dictionary() // same as above +var emptyMutableDictionary = [String: Float]() // var == mutable // @@ -165,14 +168,16 @@ do { } while 1 == 2 // Switch +// Very powerful, think `if` statements with syntax candy +// They support String, object instances, and primitives (Int, Double, etc) let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." -case let x where x.hasSuffix("pepper"): - let vegetableComment = "Is it a spicy \(x)?" +case let localScopeValue where localScopeValue.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(localScopeValue)?" default: // required (in order to cover all possible input) let vegetableComment = "Everything tastes good in soup." } @@ -186,21 +191,28 @@ default: // required (in order to cover all possible input) // in functions and can be passed around // Function with Swift header docs (format as reStructedText) + /** -A greet operation + A greet operation -- A bullet in docs -- Another bullet in the docs + - A bullet in docs + - Another bullet in the docs -:param: name A name -:param: day A day -:returns: A string containing the name and day value. + :param: name A name + :param: day A day + :returns: A string containing the name and day value. */ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } greet("Bob", "Tuesday") +// similar to above except for the function parameter behaviors +func greet2(#requiredName: String, externalParamName localParamName: String) -> String { + return "Hello \(requiredName), the day is \(localParamName)" +} +greet2(requiredName:"John", externalParamName: "Sunday") + // Function that returns multiple items in a tuple func getGasPrices() -> (Double, Double, Double) { return (3.59, 3.69, 3.79) @@ -281,7 +293,7 @@ print(numbers) // [3, 6, 18] // Structures and classes have very similar capabilites struct NamesTable { - let names: [String] + let names = [String]() // Custom subscript subscript(index: Int) -> String { @@ -291,8 +303,8 @@ struct NamesTable { // Structures have an auto-generated (implicit) designated initializer let namesTable = NamesTable(names: ["Me", "Them"]) -//let name = namesTable[2] -//println("Name is \(name)") // Name is Them +let name = namesTable[1] +println("Name is \(name)") // Name is Them // // MARK: Classes @@ -341,7 +353,7 @@ internal class Rect: Shape { init(sideLength: Int) { self.sideLength = sideLength - // always super.init last when init custom properties + // always super.init last when init custom properties super.init() } @@ -368,6 +380,9 @@ print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 +// cast instance +let aShape = mySquare as Shape + // compare instances, not the same as == which compares objects (equal to) if mySquare === mySquare { println("Yep, it's mySquare") @@ -393,6 +408,17 @@ enum Suit { } } +// Enum values allow short hand syntax, no need to type the enum type +// when the variable is explicitly declared +var suitValue: Suit = .Hearts + +// Non-Integer enums require direct raw value assignments +enum BookName: String { + case John = "John" + case Luke = "Luke" +} +println("Name: \(BookName.John.rawValue)") + // // MARK: Protocols @@ -490,5 +516,4 @@ println(mySquare.sideLength) // 4 // change side length using custom !!! operator, increases size by 3 !!!mySquare println(mySquare.sideLength) // 12 - ``` -- cgit v1.2.3 From 3fa59915d0e30b5b0f08bea5e1a62b73f4250ebb Mon Sep 17 00:00:00 2001 From: yelite Date: Sun, 18 Jan 2015 16:06:48 +0800 Subject: Update swift.html.markdown --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 0d1d2df4..2fbbe544 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -481,7 +481,7 @@ extension Int { } println(7.customProperty) // "This is 7" -println(14.multiplyBy(2)) // 42 +println(14.multiplyBy(3)) // 42 // Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. -- cgit v1.2.3 From 7a55b4a9b1badebd4b9342304c902fde049dd172 Mon Sep 17 00:00:00 2001 From: Keito Uchiyama Date: Tue, 20 Jan 2015 14:52:31 -0800 Subject: Explain Optional Chaining Without going into too much detail, mention optional chaining so it's not confusing that there is a question mark suffix (it's not currently mentioned anywhere on the page). --- swift.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 2fbbe544..c6d2a8af 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -445,7 +445,10 @@ class MyShape: Rect { func grow() { sideLength += 2 - + + // Place a question mark after an optional property, method, or + // subscript to gracefully ignore a nil value and return nil + // instead of throwing a runtime error ("optional chaining"). if let allow = self.delegate?.canReshape?() { // test for delegate then for method self.delegate?.reshaped?() -- cgit v1.2.3 From f74fd2657a6233702a46926ec79d87e46b4fa65f Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Wed, 28 Jan 2015 11:24:31 +0300 Subject: [swift/en,cn,ru]Updating the getting started guide weblink. --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index c6d2a8af..0977efc4 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -10,7 +10,7 @@ Swift is a programming language for iOS and OS X development created by Apple. D The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. -See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. +See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), which has a complete tutorial on Swift. ```swift // import a module -- cgit v1.2.3 From b178ac30776698409f6a5e8f3d9f7baf611091b6 Mon Sep 17 00:00:00 2001 From: Joey Huang Date: Sat, 28 Feb 2015 19:28:34 +0800 Subject: add optional init and enum with associated values --- swift.html.markdown | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 0977efc4..ffc57e69 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -3,6 +3,7 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] - ["Christopher Bess", "http://github.com/cbess"] + - ["Joey Huang", "http://github.com/kamidox"] filename: learnswift.swift --- @@ -388,6 +389,35 @@ if mySquare === mySquare { println("Yep, it's mySquare") } +// Optional init +class Circle: Shape { + var radius: Int + override func getArea() -> Int { + return 3 * radius * radius + } + + // Place a question mark postfix after `init` is an optional init + // which can return nil + init?(radius: Int) { + self.radius = radius + super.init() + + if radius <= 0 { + return nil + } + } +} + +var myCircle = Circle(radius: 1) +println(myCircle?.getArea()) // Optional(3) +println(myCircle!.getArea()) // 3 +var myEmptyCircle = Circle(radius: -1) +println(myEmptyCircle?.getArea()) // "nil" +if let circle = myEmptyCircle { + // will not execute since myEmptyCircle is nil + println("circle is not nil") +} + // // MARK: Enums @@ -419,6 +449,28 @@ enum BookName: String { } println("Name: \(BookName.John.rawValue)") +// Enum with associated Values +enum Furniture { + // Associate with Int + case Desk(height: Int) + // Associate with String and Int + case Chair(String, Int) + + func description() -> String { + switch self { + case .Desk(let height): + return "Desk with \(height) cm" + case .Chair(let brand, let height): + return "Chair of \(brand) with \(height) cm" + } + } +} + +var desk: Furniture = .Desk(height: 80) +println(desk.description()) // "Desk with 80 cm" +var chair = Furniture.Chair("Foo", 40) +println(chair.description()) // "Chair of Foo with 40 cm" + // // MARK: Protocols -- cgit v1.2.3 From c4558c47eaf08d7a1d22789f1b0a38c23260fd18 Mon Sep 17 00:00:00 2001 From: Anthony Nguyen Date: Mon, 3 Aug 2015 23:05:22 -0400 Subject: Println deprecated in Swift 2 --- swift.html.markdown | 56 +++++++++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 27 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index ffc57e69..8e83a0b3 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -26,7 +26,9 @@ import UIKit // TODO: Do something soon // FIXME: Fix this code -println("Hello, world") +// In Swift 2, println and print were combined into one print method. +print("Hello, world") // standard print +print("Hello, world", appendNewLine: true) // appending a new line // variables (var) value can change after being set // constants (let) value can NOT be changed after being set @@ -46,12 +48,12 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation // Build Specific values // uses -D build configuration #if false - println("Not printed") + print("Not printed") let buildValue = 3 #else let buildValue = 7 #endif -println("Build value: \(buildValue)") // Build value: 7 +print("Build value: \(buildValue)") // Build value: 7 /* Optionals are a Swift language feature that allows you to store a `Some` or @@ -69,7 +71,7 @@ var someOptionalString2: Optional = "optional" if someOptionalString != nil { // I am not nil if someOptionalString!.hasPrefix("opt") { - println("has the prefix") + print("has the prefix") } let empty = someOptionalString?.isEmpty @@ -138,21 +140,21 @@ var emptyMutableDictionary = [String: Float]() // var == mutable let myArray = [1, 1, 2, 3, 5] for value in myArray { if value == 1 { - println("One!") + print("One!") } else { - println("Not one!") + print("Not one!") } } // for loop (dictionary) var dict = ["one": 1, "two": 2] for (key, value) in dict { - println("\(key): \(value)") + print("\(key): \(value)") } // for loop (range) for i in -1...shoppingList.count { - println(i) + print(i) } shoppingList[1...2] = ["steak", "peacons"] // use ..< to exclude the last number @@ -165,7 +167,7 @@ while i < 1000 { // do-while loop do { - println("hello") + print("hello") } while 1 == 2 // Switch @@ -222,8 +224,8 @@ let pricesTuple = getGasPrices() let price = pricesTuple.2 // 3.79 // Ignore Tuple (or other) values by using _ (underscore) let (_, price1, _) = pricesTuple // price1 == 3.69 -println(price1 == pricesTuple.1) // true -println("Gas price: \(price)") +print(price1 == pricesTuple.1) // true +print("Gas price: \(price)") // Variadic Args func setup(numbers: Int...) { @@ -251,7 +253,7 @@ func swapTwoInts(inout a: Int, inout b: Int) { var someIntA = 7 var someIntB = 3 swapTwoInts(&someIntA, &someIntB) -println(someIntB) // 7 +print(someIntB) // 7 // @@ -305,7 +307,7 @@ struct NamesTable { // Structures have an auto-generated (implicit) designated initializer let namesTable = NamesTable(names: ["Me", "Them"]) let name = namesTable[1] -println("Name is \(name)") // Name is Them +print("Name is \(name)") // Name is Them // // MARK: Classes @@ -386,7 +388,7 @@ let aShape = mySquare as Shape // compare instances, not the same as == which compares objects (equal to) if mySquare === mySquare { - println("Yep, it's mySquare") + print("Yep, it's mySquare") } // Optional init @@ -409,13 +411,13 @@ class Circle: Shape { } var myCircle = Circle(radius: 1) -println(myCircle?.getArea()) // Optional(3) -println(myCircle!.getArea()) // 3 +print(myCircle?.getArea()) // Optional(3) +print(myCircle!.getArea()) // 3 var myEmptyCircle = Circle(radius: -1) -println(myEmptyCircle?.getArea()) // "nil" +print(myEmptyCircle?.getArea()) // "nil" if let circle = myEmptyCircle { // will not execute since myEmptyCircle is nil - println("circle is not nil") + print("circle is not nil") } @@ -447,7 +449,7 @@ enum BookName: String { case John = "John" case Luke = "Luke" } -println("Name: \(BookName.John.rawValue)") +print("Name: \(BookName.John.rawValue)") // Enum with associated Values enum Furniture { @@ -467,9 +469,9 @@ enum Furniture { } var desk: Furniture = .Desk(height: 80) -println(desk.description()) // "Desk with 80 cm" +print(desk.description()) // "Desk with 80 cm" var chair = Furniture.Chair("Foo", 40) -println(chair.description()) // "Chair of Foo with 40 cm" +print(chair.description()) // "Chair of Foo with 40 cm" // @@ -522,7 +524,7 @@ extension Square: Printable { } } -println("Square: \(mySquare)") +print("Square: \(mySquare)") // You can also extend built-in types extension Int { @@ -535,8 +537,8 @@ extension Int { } } -println(7.customProperty) // "This is 7" -println(14.multiplyBy(3)) // 42 +print(7.customProperty) // "This is 7" +print(14.multiplyBy(3)) // 42 // Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. @@ -550,7 +552,7 @@ func findIndex(array: [T], valueToFind: T) -> Int? { return nil } let foundAtIndex = findIndex([1, 2, 3, 4], 3) -println(foundAtIndex == 2) // true +print(foundAtIndex == 2) // true // Operators: // Custom operators can start with the characters: @@ -566,9 +568,9 @@ prefix func !!! (inout shape: Square) -> Square { } // current value -println(mySquare.sideLength) // 4 +print(mySquare.sideLength) // 4 // change side length using custom !!! operator, increases size by 3 !!!mySquare -println(mySquare.sideLength) // 12 +print(mySquare.sideLength) // 12 ``` -- cgit v1.2.3 From 775ac3b8595f80dd3229b7974672cf71d642d94f Mon Sep 17 00:00:00 2001 From: Anthony Nguyen Date: Mon, 3 Aug 2015 23:10:10 -0400 Subject: Updated print description on Swift --- swift.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 8e83a0b3..5ea8da6b 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -26,9 +26,9 @@ import UIKit // TODO: Do something soon // FIXME: Fix this code -// In Swift 2, println and print were combined into one print method. -print("Hello, world") // standard print -print("Hello, world", appendNewLine: true) // appending a new line +// In Swift 2, println and print were combined into one print method. Print automatically appends a new line. +print("Hello, world") // println is now print +print("Hello, world", appendNewLine: false) // printing without appending a newline // variables (var) value can change after being set // constants (let) value can NOT be changed after being set -- cgit v1.2.3 From d17d41a02b5eb67b0b28a9708cfa5640e17325ef Mon Sep 17 00:00:00 2001 From: Anthony Nguyen Date: Mon, 3 Aug 2015 23:11:44 -0400 Subject: Println deprecated in Swift 2, added name --- swift.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 5ea8da6b..509c9d2f 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Grant Timmerman", "http://github.com/grant"] - ["Christopher Bess", "http://github.com/cbess"] - ["Joey Huang", "http://github.com/kamidox"] + - ["Anthony Nguyen", "http://github.com/anthonyn60"] filename: learnswift.swift --- -- cgit v1.2.3 From d540d1c67bb123f8e7dc3233be957e29d8983e4b Mon Sep 17 00:00:00 2001 From: Clayton Walker Date: Tue, 6 Oct 2015 22:25:38 -0400 Subject: Original link directs to page that can't be found. Changed to represent new location of the Apple Developer tutorial on swift. --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 509c9d2f..86a0b89a 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -12,7 +12,7 @@ Swift is a programming language for iOS and OS X development created by Apple. D The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. -See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), which has a complete tutorial on Swift. +See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), which has a complete tutorial on Swift. ```swift // import a module -- cgit v1.2.3 From 960ee4a1856db8eadb96277bb2422edfa8f2a81c Mon Sep 17 00:00:00 2001 From: Gabriel Halley Date: Wed, 7 Oct 2015 23:11:24 -0400 Subject: removing whitespace all over --- swift.html.markdown | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 86a0b89a..a40e86c8 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -3,7 +3,7 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] - ["Christopher Bess", "http://github.com/cbess"] - - ["Joey Huang", "http://github.com/kamidox"] + - ["Joey Huang", "http://github.com/kamidox"] - ["Anthony Nguyen", "http://github.com/anthonyn60"] filename: learnswift.swift --- @@ -74,7 +74,7 @@ if someOptionalString != nil { if someOptionalString!.hasPrefix("opt") { print("has the prefix") } - + let empty = someOptionalString?.isEmpty } someOptionalString = nil @@ -99,7 +99,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible." /* Comment here - + /* Nested comments are also supported */ @@ -298,7 +298,7 @@ print(numbers) // [3, 6, 18] // Structures and classes have very similar capabilites struct NamesTable { let names = [String]() - + // Custom subscript subscript(index: Int) -> String { return names[index] @@ -329,7 +329,7 @@ public class Shape { internal class Rect: Shape { var sideLength: Int = 1 - + // Custom getter and setter property private var perimeter: Int { get { @@ -340,11 +340,11 @@ internal class Rect: Shape { sideLength = newValue / 4 } } - + // Lazily load a property // subShape remains nil (uninitialized) until getter called lazy var subShape = Rect(sideLength: 4) - + // If you don't need a custom getter and setter, // but still want to run code before and after getting or setting // a property, you can use `willSet` and `didSet` @@ -354,19 +354,19 @@ internal class Rect: Shape { print(someIdentifier) } } - + init(sideLength: Int) { self.sideLength = sideLength // always super.init last when init custom properties super.init() } - + func shrink() { if sideLength > 0 { --sideLength } } - + override func getArea() -> Int { return sideLength * sideLength } @@ -398,13 +398,13 @@ class Circle: Shape { override func getArea() -> Int { return 3 * radius * radius } - + // Place a question mark postfix after `init` is an optional init // which can return nil init?(radius: Int) { self.radius = radius super.init() - + if radius <= 0 { return nil } @@ -458,7 +458,7 @@ enum Furniture { case Desk(height: Int) // Associate with String and Int case Chair(String, Int) - + func description() -> String { switch self { case .Desk(let height): @@ -497,7 +497,7 @@ protocol ShapeGenerator { class MyShape: Rect { var delegate: TransformShape? - + func grow() { sideLength += 2 @@ -532,7 +532,7 @@ extension Int { var customProperty: String { return "This is \(self)" } - + func multiplyBy(num: Int) -> Int { return num * self } -- cgit v1.2.3