diff options
author | Levi Bostian <levi.bostian@gmail.com> | 2014-10-17 21:25:48 -0500 |
---|---|---|
committer | Levi Bostian <levi.bostian@gmail.com> | 2014-10-17 21:25:48 -0500 |
commit | c8da130d2d3bafedc224ba2ae516615024a0c61f (patch) | |
tree | 6d1fc70edcb025c6ee8ba3067060f8e6fddd7947 | |
parent | 115f35287fc54633cdcb0d0ba8f2fef1b9cc8921 (diff) | |
parent | 679d7098f2fe663b62e7a7e328369b760f94195c (diff) |
Merge pull request #792 from cbess/master
[swift/en] Mo betta examples
-rw-r--r-- | swift.html.markdown | 133 |
1 files changed, 109 insertions, 24 deletions
diff --git a/swift.html.markdown b/swift.html.markdown index 77047355..005e511c 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 // @@ -24,9 +27,12 @@ See also Apple's [getting started guide](https://developer.apple.com/library/pre 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 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 +40,58 @@ 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 + +// 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<T> is an enum. +*/ +var someOptionalString: String? = "optional" // Can be nil +// same as above, but ? is a postfix operator (syntax candy) +var someOptionalString2: Optional<String> = "optional" + +if someOptionalString != nil { + // I am not nil + if someOptionalString!.hasPrefix("opt") { + println("has the prefix") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +// implicitly unwrapped optional +var unwrappedString: String! = "Value is expected." +// same as above, but ! is a postfix operator (more syntax candy) +var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "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 @@ -49,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 = [ @@ -60,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 // @@ -84,9 +147,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 +187,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 +205,19 @@ greet("Bob", "Tuesday") func getGasPrices() -> (Double, Double, Double) { return (3.59, 3.69, 3.79) } +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 -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 +229,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 +282,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 +324,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 +340,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 +399,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 +407,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 +416,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 +448,7 @@ extension Int { var customProperty: String { return "This is \(self)" } - + func multiplyBy(num: Int) -> Int { return num * self } @@ -372,7 +457,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<T: Equatable>(array: [T], valueToFind: T) -> Int? { |