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

CocoaheadsSKG #1 - Introduction to Swift

CocoaheadsSKG #1 - Introduction to Swift

@tsif makes a great introduction to Swift!

CocoaHeadsSKG

January 26, 2016
Tweet

More Decks by CocoaHeadsSKG

Other Decks in Technology

Transcript

  1. About Swift • Safety • Support Cocoa and Cocoa Touch

    • Works side by side with Objective-C code • Single implementation file • Error handling, closures, multiple return values, functional programming patterns, generics, fast iteration etc. etc. etc.
  2. Variables and Constants var meetupName : String = “CocoaHeads” var

    version : Int = 3 // mutable meetupName = “CocoaHeadsSKG” let meetupCity : String = “Thessaloniki” // immutable meetupCity = “Athens” // error
  3. Variables and Constants var meetupName = “CocoaHeads” // String var

    version = 3 // Int let meetupCity = “Athens” // String let isSummer = true // Bool let π = 3.14 // Double let = " "
  4. Type aliases Type aliases define an alternative name for an

    existing type. You define type aliases with the typealias keyword.
  5. Type aliases typealias Position = (x: Int, y: Int) //

    method “overloading”, illegal in obj-c func takePosition(x: Int, y: Int) { } func takePosition(position: Position) { } takePosition(100, y: 100) takePosition(Position(x: 200, y: 100))
  6. String let myString = “I am a String” // inferred

    let theirString = myString + “!” let a = 5 let aString = “a is \(a)” // printed as “a is 5”
  7. Collection Literals var names = [“Eleni”, “Giannis”, “Luke”] var names:

    [String] = [“Eleni”, “Giannis”, “Luke”] var names: Array<String> = [“Eleni”, “Giannis”, “Luke”] var numberOfiPhones = [“Eleni”: 2, ”Luke”:0] var d: Dictionary< String, Int> = [“key1”: 1, ”key2”:2] var d: [String: Int] = [“key1”: 1, ”key2”:2]
  8. Loops while !ending { print(“looping”) } for var i =

    0; i < 10; i++ { print(i) } for number in 0...3 { print(“number \(number)” }
  9. Loops // dictionary literal + tuple for (aKey, aValue) in

    [“Eleni”: 2, ”Luke”:0] { print(“aKey \(aKey) aValue \(aValue)” }
  10. Arrays var aList = [“item0”, “item1”]; aList += “item3” aList

    += [“item4”, “item5”] aList[1] = “listItem1”
  11. Dictionaries var numberOfiPhones = [“Eleni”: 2, ”Luke”:0] numberOfiPhones[“Luke”] = 1

    var vadersPhones = numberOfiPhones[“vader”] // nil // vadersPhones is an Optional
  12. Optionals You use optionals in situations where a value may

    be absent. An optional says: • There is a value, and it equals x • There isn’t a value at all • Only
  13. Optionals • The concept of optionals doesn’t exist in C

    or Objective-C. The nearest thing in Objective-C is the ability to return nil • However, this only works for objects - it doesn’t work for structures, basic C types, or enumeration values. Requires NSNotFound or something. • Optionals in Swift work for everything
  14. Optionals var vaders: Int? = forceAwakensCharacters[“vader”] if(vaders == nil) {

    // do something } else { let count: Int = vaders! } if(vadersPhones) { let count: Int = vaders! }
  15. Optionals let cast = ["luke": 1, "wookie": 2] var vader

    : Int? = cast["vader"] if let vader = cast["vader"] { // Optional Binding } guard let vader = cast["vader"] else { break } var vader2: Int = cast["vader"]!
  16. Optionals Note: 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.
  17. If statements if myVar { print(“myVar, hurray!”) } else if

    herVar { } if(myVar) { } // braces are required
  18. Tuples • Tuples group multiple values into a single compound

    value • The values within a tuple can be of any type and do not have to be of the same type as each other.
  19. Tuples let http404Error = (404, "Not Found") // (Int, String)

    let (statusCode, statusMessage) = http404Error print("The status code is \(statusCode)") // prints "The status code is 404" print("The status message is \(statusMessage)") // prints "The status message is Not Found”
  20. Tuples let http200Status = (statusCode: 200, description: "OK") print("The status

    code is \(http200Status.statusCode)") // prints "The status code is 200" print("The status message is \(http200Status.description)") // prints "The status message is OK
  21. Switch statements switch phoneCount { case 1: print(“One phone”) case

    2,3,4: print(“More phones”) default: break } switch phoneCount { case [0, 1, 2]: print(“One phone”) case 3...6: print(“More phones”) default: break }
  22. Switch staments // There’s more! switch sender { case myTextField:

    print(“Text”) case myButton: print(“Button”) default: break }
  23. Functions func helloWorld(name: String = “John”) -> String { return

    “Hello world \(name)”; } let a: String = helloWorld()
  24. Closures • Closures are self-contained blocks of functionality that can

    be passed around and used in your code. • Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
  25. Closures Closure expression syntax has the following general form: {

    (parameters) -> return type in statements }
  26. Closures let helloSayer: () -> () in { print(“Hello World”)

    } func doTask(task: () -> ()) { } doTask(helloSayer) doTask { print(“Hello”) }
  27. Classes - Swift has no universal base class - No

    #import “Bla.h” - Type inference - ARC
  28. Properties in Classes class Animal { // methods // properties

    // initializers } class Cat : Animal { var ears = 2 // property }
  29. Properties in Classes class Cat { var description: String {

    get { return “Cat Description” } set { } } } let someCat = Cat()
  30. Initializers & Overriding class Aegean : Cat { var ears

    init() { super.init() ears = 3 } override var someFunction: String { get { return “Cat Function” } }
  31. Property Observers class Cat { init() { mouth = “Big”

    } var mouth : String { willSet { // old value available here } didSet { // new value available here } }
  32. Methods class Aegean : Cat { func jump(amount: Int) {

    for int i = 0; i < amount; i++ { print(“jump”) } } }
  33. Error handling You use error handling to respond to error

    conditions your program may encounter during execution • Determine the underlying cause of failure unlike optionals which only communicate the presence of a failure
  34. Error handling func canThrowAnError() throws { // this function may

    or may not throw an error } do { try canThrowAnError() // no error was thrown } catch { // an error was thrown }
  35. Getting started Interesting cocoa free repos Epoch // HTTP server

    for Swift 2.2 on Linux Coolie // Coolie helps you to create models (& their constructors) from JSON file Style guide