Slide 1

Slide 1 text

Introduction to Swift Part One Dimitri James Tsiflitzis CocoaHeadsSKG

Slide 2

Slide 2 text

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.

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

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

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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]

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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.

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

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.

Slide 23

Slide 23 text

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”

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

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 }

Slide 27

Slide 27 text

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

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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.

Slide 32

Slide 32 text

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

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

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

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

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

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

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 }

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

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

Slide 44

Slide 44 text

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