84
A swift introduction to Giordano Scalzo Closure Busker

A swift introduction to Swift

Embed Size (px)

DESCRIPTION

A quick introduction to Swift, the new language Apple introduced in WWDC14 to create apps for iOS and OSX

Citation preview

Page 1: A swift introduction to Swift

A swift introduction to

Giordano ScalzoClosure Busker

Page 3: A swift introduction to Swift
Page 4: A swift introduction to Swift
Page 5: A swift introduction to Swift

with different reactions

Page 6: A swift introduction to Swift
Page 7: A swift introduction to Swift
Page 8: A swift introduction to Swift
Page 9: A swift introduction to Swift

but also

Page 10: A swift introduction to Swift
Page 11: A swift introduction to Swift
Page 12: A swift introduction to Swift
Page 13: A swift introduction to Swift

From

Page 14: A swift introduction to Swift

To

Page 15: A swift introduction to Swift

What does Swift look like?

Page 16: A swift introduction to Swift
Page 17: A swift introduction to Swift
Page 18: A swift introduction to Swift
Page 19: A swift introduction to Swift
Page 20: A swift introduction to Swift
Page 21: A swift introduction to Swift
Page 22: A swift introduction to Swift
Page 23: A swift introduction to Swift

SHOW ME THE CODE!!!!!

Page 24: A swift introduction to Swift

let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } teamScore

Page 25: A swift introduction to Swift

;

Page 26: A swift introduction to Swift

;

Page 27: A swift introduction to Swift
Page 28: A swift introduction to Swift

var optionalName: String? = "John Appleseed" var greeting = "Hello!" !if optionalName { greeting = "Hello, \(optionalName!)" }

Optional

Page 29: A swift introduction to Swift

var optionalName: String? = "John Appleseed" var greeting = "Hello!" !if let name = optionalName { greeting = "Hello, \(name)" }

Optional

Page 30: A swift introduction to Swift

if let upper = john.residence?.address?.buildingIdentifier()?.uppercaseString { println("John's uppercase building identifier is \(upper).") } else { println("I can't find John's address") }

Optional Chaining

Page 31: A swift introduction to Swift

Playground

Page 32: A swift introduction to Swift
Page 33: A swift introduction to Swift

Switch on steroids

Page 34: A swift introduction to Swift

let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add raisins." case "cucumber", "watercress": let vegetableComment = "sandwich." case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?" default: let vegetableComment = "Soup." }

Page 35: A swift introduction to Swift

let somePoint = (1, 1) switch somePoint { case (0, 0): println("(0, 0) is at the origin") case (_, 0): println("(\(somePoint.0), 0) is on the x-axis") case (0, _): println("(0, \(somePoint.1)) is on the y-axis") case (-2...2, -2...2): println("(\(somePoint.0), \(somePoint.1)) is inside the box") default: println("(\(somePoint.0), \(somePoint.1)) is outside of the box") }

Page 36: A swift introduction to Swift

Functions and closures

Page 37: A swift introduction to Swift

func greet(name: String, #day: String) -> String { return "Hello \(name), today is \(day)." } greet("Bob", day: "Wednesday")

Named Parameters

Page 38: A swift introduction to Swift

func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } greet("Bob", "Wednesday")

Named Parameters Optional

Page 39: A swift introduction to Swift

Multiple result using tuples

func getGasPrices()->(Double, Double, Double) { return (3.59, 3.69, 3.79) } let (min, avg, max) = getGasPrices() println("min is \(min), max is \(max)")

Page 40: A swift introduction to Swift

Multiple result using tuples

func getGasPrices()->(Double, Double, Double) { return (3.59, 3.69, 3.79) } let gasPrices = getGasPrices() println("min is \(gasPrices.0), max is \(gasPrices.2)")

Page 41: A swift introduction to Swift

Functions are first class type

Page 42: A swift introduction to Swift

func makeIncrementer() -> (Int -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7)

A function can be a return value

Page 43: A swift introduction to Swift

or a function parameter

func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers, lessThanTen)

Page 44: A swift introduction to Swift

anonymous function

func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers, { num in num < 10})

Page 45: A swift introduction to Swift

func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers) { num in num < 10}

anonymous function

Page 46: A swift introduction to Swift

func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers) { $0 < 10}

anonymous function

Page 47: A swift introduction to Swift

Where are the classes?

Page 48: A swift introduction to Swift

class NamedShape { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } }

Page 49: A swift introduction to Swift

class Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } !let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription()

Page 50: A swift introduction to Swift

class Square: NamedShape { var sideLength: Double init(sideLength len: Double, name: String) { self.sideLength = len super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } !let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription()

Page 51: A swift introduction to Swift

class Square: NamedShape { var sideLength: Double init(_ sideLength: Double, _ name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } !let test = Square(5.2, "my test square") test.area() test.simpleDescription()

Page 52: A swift introduction to Swift

class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0 ... var perimeter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } ... }

calculated properties

Page 53: A swift introduction to Swift

class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } }

observable properties

Page 54: A swift introduction to Swift

struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } } let threeOfSpades = Card(rank: Card.Three, suit: Card.Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription()

Structs

Page 55: A swift introduction to Swift

struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } } let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription()

Structs

Page 56: A swift introduction to Swift

like classes, but passed by value...in a smarter way

Page 57: A swift introduction to Swift

classes are always passed by reference

structs are passed by reference, but automatically copied when mutated

Page 58: A swift introduction to Swift

Struct are used as ValueTypes, data components manipulated by classes

Page 59: A swift introduction to Swift

https://www.destroyallsoftware.com/talks/boundaries

Page 60: A swift introduction to Swift

enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.toRaw()) } } }

Enumerations on steroids

Page 61: A swift introduction to Swift

enum ServerResponse { case Result(String, String) case Error(String) }

Enumerations with a value associated

Page 62: A swift introduction to Swift

Enumerations with a value associated

let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Error("Out of cheese.")

Page 63: A swift introduction to Swift

Pattern matching to extract associated values

switch result { case let .Result(sunrise, sunset): let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)." case let .Error(error): let serverResponse = "Failure... \(error)" }

Page 64: A swift introduction to Swift

protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() }

Protocols... like Interface in Java or... protocols in Objective-C

Page 65: A swift introduction to Swift

extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } 7.simpleDescription

extensions... like categories in Objective-C

Page 66: A swift introduction to Swift

Generics

Page 67: A swift introduction to Swift

func repeatString(item: String, times: Int) -> String[] { var result = String[]() for i in 0..times { result += item } return result } repeatString("knock", 4)

Page 68: A swift introduction to Swift

!func repeatInt(item: Int, times: Int) -> Int[] { var result = Int[]() for i in 0..times { result += item } return result } repeatInt(42, 4)

Page 69: A swift introduction to Swift

func repeat<T>(item: T, times: Int) -> T[] { var result = T[]() for i in 0..times { result += item } return result } repeat("knock", 4) repeat(42, 3)

Page 70: A swift introduction to Swift

Operator overload@infix func +(t1: Int, t2: Int) -> Int{ return 3 } !@prefix func +(t1: Int) -> Int{ return 5 } !var a = 20 var b = 111 !a + b // 3 a - +b // 15

Page 71: A swift introduction to Swift

But the most important feature, the only one that you need to learn is...

Page 72: A swift introduction to Swift

Emoji!!!

Page 73: A swift introduction to Swift
Page 74: A swift introduction to Swift

For me (imvho) the most useful new features are enumerations and pattern

matching

Page 75: A swift introduction to Swift

Unit Test support

Page 76: A swift introduction to Swift

XCTest

class RpnCalculatorKataTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testExample() { XCTAssert(true, "Pass") } func testPerformanceExample() { self.measureBlock() { } } }

Page 77: A swift introduction to Swift

Quickclass PersonSpec: QuickSpec { override class func exampleGroups() { describe("Person") { var person: Person? beforeEach { person = Person() } describe("greeting") { context("when the person is unhappy") { beforeEach { person!.isHappy = false } it("is lukewarm") { expect(person!.greeting).to.equal("Oh, hi.") expect(person!.greeting).notTo.equal("Hello!") } } } } } }

Page 78: A swift introduction to Swift

And now...

Page 79: A swift introduction to Swift

Let's code

Page 80: A swift introduction to Swift

a Rpn Calculator

Page 81: A swift introduction to Swift

enum Key : String { case One = "1" //... case Enter = "enter" case Plus = "+" case Minus = "-" } !protocol RpnCalculator { var display : String[] { get } func press(key: Key) }

https://github.com/gscalzo/RpnCalculatorKata

Page 82: A swift introduction to Swift
Page 83: A swift introduction to Swift
Page 84: A swift introduction to Swift