diff options
Diffstat (limited to 'swift.html.markdown')
| -rw-r--r-- | swift.html.markdown | 89 | 
1 files changed, 46 insertions, 43 deletions
| diff --git a/swift.html.markdown b/swift.html.markdown index ffc57e69..a40e86c8 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -3,7 +3,8 @@ 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  --- @@ -11,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 @@ -26,7 +27,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 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 @@ -46,12 +49,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,9 +72,9 @@ var someOptionalString2: Optional<String> = "optional"  if someOptionalString != nil {      // I am not nil      if someOptionalString!.hasPrefix("opt") { -        println("has the prefix") +        print("has the prefix")      } -     +      let empty = someOptionalString?.isEmpty  }  someOptionalString = nil @@ -96,7 +99,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible."  /*      Comment here -     +      /*          Nested comments are also supported      */ @@ -138,21 +141,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 +168,7 @@ while i < 1000 {  // do-while loop  do { -    println("hello") +    print("hello")  } while 1 == 2  // Switch @@ -222,8 +225,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 +254,7 @@ func swapTwoInts(inout a: Int, inout b: Int) {  var someIntA = 7  var someIntB = 3  swapTwoInts(&someIntA, &someIntB) -println(someIntB) // 7 +print(someIntB) // 7  // @@ -295,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] @@ -305,7 +308,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 @@ -326,7 +329,7 @@ public class Shape {  internal class Rect: Shape {      var sideLength: Int = 1 -     +      // Custom getter and setter property      private var perimeter: Int {          get { @@ -337,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` @@ -351,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      } @@ -386,7 +389,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 @@ -395,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          } @@ -409,13 +412,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 +450,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 { @@ -455,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): @@ -467,9 +470,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"  // @@ -494,7 +497,7 @@ protocol ShapeGenerator {  class MyShape: Rect {      var delegate: TransformShape? -     +      func grow() {          sideLength += 2 @@ -522,21 +525,21 @@ extension Square: Printable {      }  } -println("Square: \(mySquare)") +print("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(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 +553,7 @@ func findIndex<T: Equatable>(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 +569,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  ``` | 
