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. Introduction to Swift
    Part One
    Dimitri James Tsiflitzis
    CocoaHeadsSKG

    View Slide

  2. 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.

    View Slide

  3. Hello world in Objective-C
    #import
    int main(void) {
    NSLog(@"Hello, world!\n");
    return 0;
    }

    View Slide

  4. Hello world in Swift
    print(“Hello World!”)

    View Slide

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

    View Slide

  6. Variables and Constants
    var meetupName = “CocoaHeads” // String
    var version = 3 // Int
    let meetupCity = “Athens” // String
    let isSummer = true // Bool
    let π = 3.14 // Double
    let = " "

    View Slide

  7. Type aliases
    Type aliases define an alternative name for an
    existing type. You define type aliases with the
    typealias keyword.

    View Slide

  8. Type aliases
    typealias AudioSample = UInt16
    var maxAmplitudeFound = AudioSample.min
    // maxAmplitudeFound is now 0”

    View Slide

  9. 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))

    View Slide

  10. String
    let myString = “I am a String” // inferred
    let theirString = myString + “!”
    let a = 5
    let aString = “a is \(a)”
    // printed as “a is 5”

    View Slide

  11. Collection Literals
    var names = [“Eleni”, “Giannis”, “Luke”]
    var names: [String] = [“Eleni”, “Giannis”, “Luke”]
    var names: Array = [“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]

    View Slide

  12. Loops
    while !ending {
    print(“looping”)
    }
    for var i = 0; i < 10; i++ {
    print(i)
    }
    for number in 0...3 {
    print(“number \(number)”
    }

    View Slide

  13. Loops
    // dictionary literal + tuple
    for (aKey, aValue) in [“Eleni”: 2, ”Luke”:0] {
    print(“aKey \(aKey) aValue \(aValue)”
    }

    View Slide

  14. Arrays
    var aList = [“item0”, “item1”];
    aList += “item3”
    aList += [“item4”, “item5”]
    aList[1] = “listItem1”

    View Slide

  15. Dictionaries
    var numberOfiPhones = [“Eleni”: 2, ”Luke”:0]
    numberOfiPhones[“Luke”] = 1
    var vadersPhones = numberOfiPhones[“vader”]
    // nil
    // vadersPhones is an Optional

    View Slide

  16. 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

    View Slide

  17. 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

    View Slide

  18. Optionals
    var vaders: Int? = forceAwakensCharacters[“vader”]
    if(vaders == nil) {
    // do something
    } else {
    let count: Int = vaders!
    }
    if(vadersPhones) {
    let count: Int = vaders!
    }

    View Slide

  19. 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"]!

    View Slide

  20. 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.

    View Slide

  21. If statements
    if myVar {
    print(“myVar, hurray!”)
    } else if herVar {
    }
    if(myVar) {
    }
    // braces are required

    View Slide

  22. 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.

    View Slide

  23. 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”

    View Slide

  24. 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

    View Slide

  25. Tuples
    Pro Tip:
    Share data structure without sharing code with
    tuples

    View Slide

  26. 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
    }

    View Slide

  27. Switch staments
    // There’s more!
    switch sender {
    case myTextField:
    print(“Text”)
    case myButton:
    print(“Button”)
    default:
    break
    }

    View Slide

  28. Functions
    func helloWorld {
    print(“Hello world”)
    }
    helloWorld() // prints ‘Hello World’

    View Slide

  29. Functions
    func helloWorld(name: String = “John”) {
    print(“Hello world \(name)”);
    }
    helloWorld() // prints ‘Hello World John’

    View Slide

  30. Functions
    func helloWorld(name: String = “John”) -> String {
    return “Hello world \(name)”;
    }
    let a: String = helloWorld()

    View Slide

  31. 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.

    View Slide

  32. Closures
    Closure expression syntax has the following
    general form:
    { (parameters) -> return type in
    statements
    }

    View Slide

  33. Closures
    let helloSayer: () -> () in {
    print(“Hello World”)
    }
    func doTask(task: () -> ()) {
    }
    doTask(helloSayer)
    doTask { print(“Hello”) }

    View Slide

  34. Classes
    - Swift has no universal base class
    - No #import “Bla.h”
    - Type inference
    - ARC

    View Slide

  35. Properties in Classes
    class Animal {
    // methods
    // properties
    // initializers
    }
    class Cat : Animal {
    var ears = 2 // property
    }

    View Slide

  36. Properties in Classes
    class Cat {
    var description: String {
    get {
    return “Cat Description”
    }
    set {
    }
    }
    }
    let someCat = Cat()

    View Slide

  37. Initializers & Overriding
    class Aegean : Cat {
    var ears
    init() {
    super.init()
    ears = 3
    }
    override var someFunction: String {
    get {
    return “Cat Function”
    }
    }

    View Slide

  38. Property Observers
    class Cat {
    init() {
    mouth = “Big”
    }
    var mouth : String {
    willSet {
    // old value available here
    }
    didSet {
    // new value available here
    }
    }

    View Slide

  39. Methods
    class Aegean : Cat {
    func jump(amount: Int) {
    for int i = 0; i < amount; i++ {
    print(“jump”)
    }
    }
    }

    View Slide

  40. 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

    View Slide

  41. 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
    }

    View Slide

  42. Getting started
    https://swift.org/getting-started/
    Ray Tutorial
    OSX & Linux support
    No Cocoa for Linux ( ͡° ͜ʖ ͡°)

    View Slide

  43. 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

    View Slide

  44. Ευχαριστούμε :)
    Dimitri James Tsiflitzis
    nimber, taxibeat, stonesoup, peopleperhour
    @sprimp
    github.com/tsif

    View Slide