From 5dac348b72000dedc2e8a35f1ccaea55a7f408f7 Mon Sep 17 00:00:00 2001 From: Clayton Walker Date: Tue, 6 Oct 2015 23:00:11 -0400 Subject: Forgot to add myself as a contributor from swift-1 pull request. --- 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 509c9d2f..23ebcfc5 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Christopher Bess", "http://github.com/cbess"] - ["Joey Huang", "http://github.com/kamidox"] - ["Anthony Nguyen", "http://github.com/anthonyn60"] + - ["Clayton Walker", "https://github.com/cwalk"] filename: learnswift.swift --- -- cgit v1.2.3 From ad16a31c0751f244a46cadbfb3540943af73349d Mon Sep 17 00:00:00 2001 From: Clayton Walker Date: Tue, 6 Oct 2015 23:36:32 -0400 Subject: Added clearer description of Optionals and Unwrapping. Minor typo changes as well. --- swift.html.markdown | 43 +++++++++++++++++++++++++------------------ 1 file changed, 25 insertions(+), 18 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 23ebcfc5..46e5e6d4 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -58,8 +58,9 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation print("Build value: \(buildValue)") // Build value: 7 /* - Optionals are a Swift language feature that allows you to store a `Some` or - `None` value. + Optionals are a Swift language feature that either contains a value, + or contains nil (no value) to indicate that a value is missing. + A question mark (?) after the type marks the value as optional. Because Swift requires every property to have a value, even nil must be explicitly stored as an Optional value. @@ -75,11 +76,17 @@ if someOptionalString != nil { if someOptionalString!.hasPrefix("opt") { print("has the prefix") } - + let empty = someOptionalString?.isEmpty } someOptionalString = nil +/* + To get the underlying type from an optional, you unwrap it using the + force unwrap operator (!). Only use the unwrap operator if you're sure + the underlying value isn't nil. +*/ + // implicitly unwrapped optional var unwrappedString: String! = "Value is expected." // same as above, but ! is a postfix operator (more syntax candy) @@ -94,13 +101,13 @@ if let someOptionalStringConstant = someOptionalString { // 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) +// 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 - + /* Nested comments are also supported */ @@ -296,10 +303,10 @@ print(numbers) // [3, 6, 18] // MARK: Structures // -// Structures and classes have very similar capabilites +// Structures and classes have very similar capabilities struct NamesTable { let names = [String]() - + // Custom subscript subscript(index: Int) -> String { return names[index] @@ -330,7 +337,7 @@ public class Shape { internal class Rect: Shape { var sideLength: Int = 1 - + // Custom getter and setter property private var perimeter: Int { get { @@ -341,11 +348,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` @@ -355,19 +362,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 } @@ -399,13 +406,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 } @@ -459,7 +466,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): @@ -498,7 +505,7 @@ protocol ShapeGenerator { class MyShape: Rect { var delegate: TransformShape? - + func grow() { sideLength += 2 @@ -533,7 +540,7 @@ extension Int { var customProperty: String { return "This is \(self)" } - + func multiplyBy(num: Int) -> Int { return num * self } -- 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 From 707c8db171cb5239682332f14fd2098901741c63 Mon Sep 17 00:00:00 2001 From: Valentine Silvansky Date: Thu, 8 Oct 2015 10:00:13 +0300 Subject: Add generics operator in Swift --- swift.html.markdown | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index a40e86c8..75535e43 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -574,4 +574,18 @@ print(mySquare.sideLength) // 4 // change side length using custom !!! operator, increases size by 3 !!!mySquare print(mySquare.sideLength) // 12 + +// Operators can also be generics +infix operator <-> {} +func <-> (inout a: T, inout b: T) { + let c = a + a = b + b = c +} + +var foo: Float = 10 +var bar: Float = 20 + +foo <-> bar +print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0" ``` -- cgit v1.2.3 From b4860de42f2bbf0ab97ef28085eb40accb030657 Mon Sep 17 00:00:00 2001 From: Clayton Walker Date: Thu, 8 Oct 2015 23:27:19 -0400 Subject: Suggested changes --- swift.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 46e5e6d4..9f0019d8 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -58,8 +58,8 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation print("Build value: \(buildValue)") // Build value: 7 /* - Optionals are a Swift language feature that either contains a value, - or contains nil (no value) to indicate that a value is missing. + Optionals are a Swift language feature that either contains a value, + or contains nil (no value) to indicate that a value is missing. A question mark (?) after the type marks the value as optional. Because Swift requires every property to have a value, even nil must be @@ -82,9 +82,9 @@ if someOptionalString != nil { someOptionalString = nil /* - To get the underlying type from an optional, you unwrap it using the - force unwrap operator (!). Only use the unwrap operator if you're sure - the underlying value isn't nil. + Trying to use ! to access a non-existent optional value triggers a runtime + error. Always make sure that an optional contains a non-nil value before + using ! to force-unwrap its value. */ // implicitly unwrapped optional -- cgit v1.2.3 From 9530122a1c956a25adb71bfd9cc1c516ff67d2f3 Mon Sep 17 00:00:00 2001 From: Fernando Valverde Date: Fri, 30 Oct 2015 22:43:44 +0100 Subject: Include MARK style and two collection declarations Added MARK with separator and a couple of mutable explicit declarations of empty Array/Dictionary --- swift.html.markdown | 3 +++ 1 file changed, 3 insertions(+) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index f451288d..1ca81bc2 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -25,6 +25,7 @@ import UIKit // Xcode supports landmarks to annotate your code and lists them in the jump bar // MARK: Section mark +// MARK: - Section mark with a separator line // TODO: Do something soon // FIXME: Fix this code @@ -128,6 +129,7 @@ shoppingList[1] = "bottle of water" let emptyArray = [String]() // let == immutable let emptyArray2 = Array() // same as above var emptyMutableArray = [String]() // var == mutable +var explicitEmptyMutableStringArray: [String] = [] // same as above // Dictionary @@ -139,6 +141,7 @@ occupations["Jayne"] = "Public Relations" let emptyDictionary = [String: Float]() // let == immutable let emptyDictionary2 = Dictionary() // same as above var emptyMutableDictionary = [String: Float]() // var == mutable +var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above // -- cgit v1.2.3 From dbe6184519860e526432c4987a6f67d6c0acf38e Mon Sep 17 00:00:00 2001 From: Fernando Valverde Arredondo Date: Sun, 1 Nov 2015 01:48:44 +0100 Subject: Update contributor list --- swift.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 1ca81bc2..f3746613 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Joey Huang", "http://github.com/kamidox"] - ["Anthony Nguyen", "http://github.com/anthonyn60"] - ["Clayton Walker", "https://github.com/cwalk"] + - ["Fernando Valverde", "http://visualcosita.xyz"] filename: learnswift.swift --- @@ -25,7 +26,7 @@ import UIKit // Xcode supports landmarks to annotate your code and lists them in the jump bar // MARK: Section mark -// MARK: - Section mark with a separator line +// MARK: - Section mark with a separator line // TODO: Do something soon // FIXME: Fix this code @@ -83,7 +84,7 @@ if someOptionalString != nil { someOptionalString = nil /* - Trying to use ! to access a non-existent optional value triggers a runtime + Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value. */ -- cgit v1.2.3 From afc5ea14654e0e9cd11c7ef1b672639d12418bad Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Mon, 9 Nov 2015 17:54:05 -0600 Subject: - update examples - add examples for labeled tuples and computed properties --- swift.html.markdown | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index 0d1d2df4..5e6b76e6 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -211,7 +211,7 @@ greet("Bob", "Tuesday") func greet2(#requiredName: String, externalParamName localParamName: String) -> String { return "Hello \(requiredName), the day is \(localParamName)" } -greet2(requiredName:"John", externalParamName: "Sunday") +greet2(requiredName: "John", externalParamName: "Sunday") // Function that returns multiple items in a tuple func getGasPrices() -> (Double, Double, Double) { @@ -224,6 +224,16 @@ let (_, price1, _) = pricesTuple // price1 == 3.69 println(price1 == pricesTuple.1) // true println("Gas price: \(price)") +// Named tuple params +func getGasPrices2() -> (lowestPrice: Double, highestPrice: Double, midPrice: Double) { + return (1.77, 37.70, 7.37) +} +let pricesTuple2 = getGasPrices2() +let price2 = pricesTuple2.lowestPrice +let (_, price3, _) = pricesTuple2 +println(pricesTuple2.highestPrice == pricesTuple2.1) // true +println("Highest gas price: \(pricesTuple2.highestPrice)") + // Variadic Args func setup(numbers: Int...) { // its an array @@ -337,6 +347,11 @@ internal class Rect: Shape { } } + // Computed properties must be declared as `var`, you know, cause they can change + var smallestSideLength: Int { + return self.sideLength - 1 + } + // Lazily load a property // subShape remains nil (uninitialized) until getter called lazy var subShape = Rect(sideLength: 4) -- cgit v1.2.3 From 618f8f5badfded04ee1edb7c24ccf24ea61a947b Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Mon, 9 Nov 2015 18:09:48 -0600 Subject: - update Swift examples - update to upgrade to Swift 2.1 - code cleanup --- swift.html.markdown | 81 +++++++++++++++++++++++++---------------------------- 1 file changed, 38 insertions(+), 43 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index f2e9d04c..a39bc1d6 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -32,7 +32,7 @@ import UIKit // 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 +print("Hello, world", terminator: "") // printing without appending a newline // variables (var) value can change after being set // constants (let) value can NOT be changed after being set @@ -60,14 +60,14 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation print("Build value: \(buildValue)") // Build value: 7 /* - Optionals are a Swift language feature that either contains a value, - or contains nil (no value) to indicate that a value is missing. - A question mark (?) after the type marks the value as optional. +Optionals are a Swift language feature that either contains a value, +or contains nil (no value) to indicate that a value is missing. +A question mark (?) after the type marks the value as optional. - Because Swift requires every property to have a value, even nil must be - explicitly stored as an Optional value. +Because Swift requires every property to have a value, even nil must be +explicitly stored as an Optional value. - Optional is an enum. +Optional is an enum. */ var someOptionalString: String? = "optional" // Can be nil // same as above, but ? is a postfix operator (syntax candy) @@ -84,9 +84,9 @@ if someOptionalString != nil { someOptionalString = nil /* - Trying to use ! to access a non-existent optional value triggers a runtime - error. Always make sure that an optional contains a non-nil value before - using ! to force-unwrap its value. +Trying to use ! to access a non-existent optional value triggers a runtime +error. Always make sure that an optional contains a non-nil value before +using ! to force-unwrap its value. */ // implicitly unwrapped optional @@ -120,8 +120,8 @@ anyObjectVar = "Changed value to a string, not good practice, but possible." // /* - 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 and Dictionary types are structs. So `let` and `var` also indicate +that they are mutable (var) or immutable (let) when declaring these types. */ // Array @@ -178,8 +178,8 @@ while i < 1000 { i *= 2 } -// do-while loop -do { +// repeat-while loop +repeat { print("hello") } while 1 == 2 @@ -209,22 +209,22 @@ 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)." } -greet("Bob", "Tuesday") +greet("Bob", day: "Tuesday") // similar to above except for the function parameter behaviors -func greet2(#requiredName: String, externalParamName localParamName: String) -> String { +func greet2(requiredName requiredName: String, externalParamName localParamName: String) -> String { return "Hello \(requiredName), the day is \(localParamName)" } greet2(requiredName: "John", externalParamName: "Sunday") @@ -247,14 +247,14 @@ func getGasPrices2() -> (lowestPrice: Double, highestPrice: Double, midPrice: Do let pricesTuple2 = getGasPrices2() let price2 = pricesTuple2.lowestPrice let (_, price3, _) = pricesTuple2 -println(pricesTuple2.highestPrice == pricesTuple2.1) // true -println("Highest gas price: \(pricesTuple2.highestPrice)") +print(pricesTuple2.highestPrice == pricesTuple2.1) // true +print("Highest gas price: \(pricesTuple2.highestPrice)") // Variadic Args func setup(numbers: Int...) { // its an array - let number = numbers[0] - let argCount = numbers.count + let _ = numbers[0] + let _ = numbers.count } // Passing and returning functions @@ -275,7 +275,7 @@ func swapTwoInts(inout a: Int, inout b: Int) { } var someIntA = 7 var someIntB = 3 -swapTwoInts(&someIntA, &someIntB) +swapTwoInts(&someIntA, b: &someIntB) print(someIntB) // 7 @@ -303,23 +303,17 @@ numbers = numbers.map({ number in 3 * number }) print(numbers) // [3, 6, 18] // Trailing closure -numbers = sorted(numbers) { $0 > $1 } +numbers = numbers.sort { $0 > $1 } print(numbers) // [18, 6, 3] -// Super shorthand, since the < operator infers the types - -numbers = sorted(numbers, < ) - -print(numbers) // [3, 6, 18] - // // MARK: Structures // // Structures and classes have very similar capabilities struct NamesTable { - let names = [String]() + let names: [String] // Custom subscript subscript(index: Int) -> String { @@ -472,9 +466,10 @@ enum Suit { // when the variable is explicitly declared var suitValue: Suit = .Hearts -// Non-Integer enums require direct raw value assignments +// String enums can have direct raw value assignments +// or their raw values will be derived from the Enum field enum BookName: String { - case John = "John" + case John case Luke = "Luke" } print("Name: \(BookName.John.rawValue)") @@ -518,7 +513,7 @@ protocol ShapeGenerator { // Protocols declared with @objc allow optional functions, // which allow you to check for conformance @objc protocol TransformShape { - optional func reshaped() + optional func reshape() optional func canReshape() -> Bool } @@ -531,9 +526,9 @@ class MyShape: Rect { // 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?() { + if let reshape = self.delegate?.canReshape?() where reshape { // test for delegate then for method - self.delegate?.reshaped?() + self.delegate?.reshape?() } } } @@ -546,7 +541,7 @@ class MyShape: Rect { // `extension`s: Add extra functionality to an already existing type // Square now "conforms" to the `Printable` protocol -extension Square: Printable { +extension Square: CustomStringConvertible { var description: String { return "Area: \(self.getArea()) - ID: \(self.identifier)" } @@ -571,8 +566,8 @@ print(14.multiplyBy(3)) // 42 // Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. -func findIndex(array: [T], valueToFind: T) -> Int? { - for (index, value) in enumerate(array) { +func findIndex(array: [T], _ valueToFind: T) -> Int? { + for (index, value) in array.enumerate() { if value == valueToFind { return index } -- cgit v1.2.3 From 99b2c3db3705b5231ca360c9fa69c8319caab69b Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Tue, 10 Nov 2015 17:03:40 -0600 Subject: - add where and guard examples --- swift.html.markdown | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index a39bc1d6..df9c5092 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -149,6 +149,14 @@ var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above // MARK: Control Flow // +// Condition statements support "where" clauses, which can be used +// to help provide conditions on optional values. +// Both the assignment and the "where" clause must pass. +let someNumber = Optional(7) +if let num = someNumber where num > 3 { + print("num is greater than 3") +} + // for loop (array) let myArray = [1, 1, 2, 3, 5] for value in myArray { @@ -198,7 +206,6 @@ default: // required (in order to cover all possible input) let vegetableComment = "Everything tastes good in soup." } - // // MARK: Functions // @@ -240,7 +247,7 @@ let (_, price1, _) = pricesTuple // price1 == 3.69 print(price1 == pricesTuple.1) // true print("Gas price: \(price)") -// Named tuple params +// Labeled/named tuple params func getGasPrices2() -> (lowestPrice: Double, highestPrice: Double, midPrice: Double) { return (1.77, 37.70, 7.37) } @@ -250,6 +257,18 @@ let (_, price3, _) = pricesTuple2 print(pricesTuple2.highestPrice == pricesTuple2.1) // true print("Highest gas price: \(pricesTuple2.highestPrice)") +// guard statements +func testGuard() { + // guards provide early exits or breaks, placing the error handler code near the conditions. + // it places variables it declares in the same scope as the guard statement. + guard let aNumber = Optional(7) else { + return + } + + print("number is \(aNumber)") +} +testGuard() + // Variadic Args func setup(numbers: Int...) { // its an array -- cgit v1.2.3 From 312941c5e018bee87be524697b471061cf70b285 Mon Sep 17 00:00:00 2001 From: Rob Pilling Date: Fri, 13 Nov 2015 14:52:21 +0000 Subject: Correct "Casting" mention in swift markdown 'T()' is initialisation/creation, 'x as T' is casting --- 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 df9c5092..e3934ab1 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -46,7 +46,7 @@ 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 label = "some text " + String(myVariable) // String construction let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation // Build Specific values -- cgit v1.2.3 From 50fca171c53ca5c1de63c9a09ca457df0767f713 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Mon, 23 Nov 2015 13:12:49 -0600 Subject: - added error handling example - add do-try-catch examples - add throw example --- swift.html.markdown | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) (limited to 'swift.html.markdown') diff --git a/swift.html.markdown b/swift.html.markdown index df9c5092..33ff8451 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -345,6 +345,44 @@ let namesTable = NamesTable(names: ["Me", "Them"]) let name = namesTable[1] print("Name is \(name)") // Name is Them +// +// MARK: Error Handling +// + +// The `ErrorType` protocol is used when throwing errors to catch +enum MyError: ErrorType { + case BadValue(msg: String) + case ReallyBadValue(msg: String) +} + +// functions marked with `throws` must be called using `try` +func fakeFetch(value: Int) throws -> String { + guard 7 == value else { + throw MyError.ReallyBadValue(msg: "Some really bad value") + } + + return "test" +} + +func testTryStuff() { + // assumes there will be no error thrown, otherwise a runtime exception is raised + let _ = try! fakeFetch(7) + + // if an error is thrown, then it proceeds, but if the value is nil + // it also wraps every return value in an optional, even if its already optional + let _ = try? fakeFetch(7) + + do { + // normal try operation that provides error handling via `catch` block + try fakeFetch(1) + } catch MyError.BadValue(let msg) { + print("Error message: \(msg)") + } catch { + // must be exhaustive + } +} +testTryStuff() + // // MARK: Classes // @@ -559,7 +597,7 @@ class MyShape: Rect { // `extension`s: Add extra functionality to an already existing type -// Square now "conforms" to the `Printable` protocol +// Square now "conforms" to the `CustomStringConvertible` protocol extension Square: CustomStringConvertible { var description: String { return "Area: \(self.getArea()) - ID: \(self.identifier)" -- cgit v1.2.3