Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Swift Workshop

puls
June 10, 2014

Swift Workshop

What you need to know about Apple's new language.

puls

June 10, 2014
Tweet

More Decks by puls

Other Decks in Technology

Transcript

  1. Range operator for i in 1..3 { print(i) } //

    prints 12 for i in 1...3 { print(i) } // prints 123
  2. class Person { var firstName : String = "" var

    lastName : String = "" var fullName : String { get { return "\(firstName) \(lastName)" } set { let parts = newValue.componentsSeparatedByString(" ") firstName = parts[0] lastName = parts[1] } } } Getters and setters
  3. enum ComparisonResult { case Ascending case Equal case Descending }

    ! typealias Comparator = (Int, Int) -> ComparisonResult func sortArray(array : Int[], compareFunction : Comparator) { // ... } Static type system
  4. enum ComparisonResult { case Ascending case Equal case Descending }

    ! func sortArray<T>(array : T[], compareFunction : (T, T) -> ComparisonResult) { // ... } Generics
  5. enum FlightStatus { case OnTime // Sweet case Delayed(Int) //

    Oh well case UnitedAirlines // Should have known } Parameterized Enums
  6. struct Rect { let height : Double let width :

    Double var area : Double { return height * width } } ! let r = Rect(height: 4, width: 8) r.area // 32.0 Structs with behavior
  7. let a : Any = 124 let b = 346

    ! switch (a, b) { case (_, 345): println("b is 345") case (is Int, _): println("a is Int") default: println("nothing matched") } Pattern Matching
  8. let a = 1 var b = 2 b =

    3 a = 3 // error ! let c = [1,2,3] // fixed-size array var d = [1,2,3] // mutable array c += 4 // error d += 4 ! c[1] = 4 // this works, though Constants and variables
  9. func madLibs(a : String, b : String = "Second", c

    : String = "Third") { println("\(a) then \(b) then \(c)") } madLibs("foo", b: "bar", c: "baz") madLibs("yep") Default parameter values
  10. extension Int { subscript(index : Int) -> Int { get

    { return self % index } } } Subscripting
  11. extension Int { func times(closure : () -> ()) {

    for _ in 0..self { closure() } } } ! 3.times() { println("Swift is the best!") } “Trailing closure” syntax
  12. var numbers = [1,5,2,9,3,4,6,8,7] numbers.sort({ a, b in a <

    b }) numbers.sort { a, b in a < b } Syntactic sugar
  13. var numbers = [1,5,2,9,3,4,6,8,7] numbers.sort({ a, b in a <

    b }) numbers.sort { a, b in a < b } numbers.sort { $0 < $1 } Syntactic sugar
  14. var numbers = [1,5,2,9,3,4,6,8,7] numbers.sort({ a, b in a <

    b }) numbers.sort { a, b in a < b } numbers.sort { $0 < $1 } numbers.sort(<) Syntactic sugar
  15. var a : Int? var b : Int ! a

    // nil a = 1 // {Some 1} a + 2 // this is an error a! + 2 // 3 b = 2 // 2 b + 2 // 4 Optionals