Slide 1

Slide 1 text

Why Swift? A practical intro to thinking functionally

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

Why Swift? We ❤ Objective C! • Optionals • Result • Deferred

Slide 8

Slide 8 text

Optionals: they’re a PITA

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

2015-04-02 12:28:56.882 Wallapop[3066:91913] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

As a physical manifestation of a logical system, computers are faced with the intractable problem of how to represent nothing with something Mattt Thompson

Slide 19

Slide 19 text

Benefits of optionals • Reduces the cognitive load when dealing with objects and APIs you did not write - No more maintenance code like Assertions when an API is called incorrectly or an object is initialised incorrectly

Slide 20

Slide 20 text

Drawbacks of optionals • PITA to write sometimes: use Undefined - https://github.com/weissi/swift-undefined • Interaction with Cocoa APIs is weird sometimes - Things are getting better with every release

Slide 21

Slide 21 text

Objective C improvements • Apple introduced __nullable and __nonnull Released with Xcode 6.3

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

Result: monads for the rest of us

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

NSError *err = nil; CGFloat result = [NMArithmetic divide:2.5 by:3.0 error:&err]; if (err) { NSLog(@"%@", err) } else { [NMArithmetic doSomethingWithResult:result] }

Slide 26

Slide 26 text

Result • Allows us to express with clarity what are the expected results from an function: enum Result { case Success(T) case Failure(ErrorType) } https://www.youtube.com/watch?v=LqwrUmuodyY

Slide 27

Slide 27 text

func divide (dividend : Float, divisor : Float) -> Result let result = divide(dividend :2.5, divisor:3) switch result { case .Success(let quotient): doSomethingWithResult(quotient) case .Failure(let error): print(error) }

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

Result: Chaining func map(f: T -> U) -> Result { switch self { case .Failure(let error): return .Failure(error) case .Success(let value): return .Success(f(value)) } }

Slide 30

Slide 30 text

Result: Chaining func fetchImageData(url : NSURL) -> Result func processImageData(data : NSData) -> UIImage let imageResult = fetchImageData().map(processImageData)

Slide 31

Slide 31 text

Result: Chaining

Slide 32

Slide 32 text

Result: Chaining func bind(f: T -> Result) -> Result { switch self { case .Failure(let error): return .Failure(error) case .Success(let value): return f(value) } }

Slide 33

Slide 33 text

func fetchWallData () -> Result { let mainBundle = NSBundle.mainBundle() guard let url = mainBundle.URLForResource("wall", withExtension: "json") else { return .Failure(NSError()) } guard let data = NSData(contentsOfURL: url) else { return .Failure(NSError()) } return .Success(data) }

Slide 34

Slide 34 text

func parseWallData(data : NSData) -> Result { let jsonObject : AnyObject do { jsonObject = try NSJSONSerialization .JSONObjectWithData(data, options: .MutableContainers) } catch let error { return .Failure(error as NSError) } guard let jsonResult = jsonObject as? [String : AnyObject] else { return .Failure(NSError()) } guard let page = parseWallPage(jsonResult) else { return Result(NSError()) } return .Success(page) }

Slide 35

Slide 35 text

Result: Chaining func fetchWallData () -> Result func parseWallData(data : NSData) -> Result let pageResult = fetchWallData().bind(parseWallData)

Slide 36

Slide 36 text

Happy Path Programming!!!

Slide 37

Slide 37 text

Deferred: functional concurrency

Slide 38

Slide 38 text

What about the error?

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

No content

Slide 41

Slide 41 text

Deferred class Deferred { init() init(value:T) var isFilled: Bool func fill (value : T) func peek () -> T func upon (block : T -> ()) }

Slide 42

Slide 42 text

Deferred extension Deferred { func map(f: T -> U) -> Deferred func bind(f: T -> Deferred) -> Deferred }

Slide 43

Slide 43 text

Deferred • Can be used trivially whenever a completionBlock was being used. ✓ When calling upon, you can schedule a closure on any GCD queue, and, unlike completionBlocks in ObjC, multiple closures can be scheduled to be executed.

Slide 44

Slide 44 text

Deferred func both(other: Deferred) -> Deferred<(T,U)> func all(deferreds: [Deferred]) -> Deferred<[T]> func any(deferreds: [Deferred]) -> Deferred>

Slide 45

Slide 45 text

Deferred func fetchProductsInContext(context : NSManagedObjectContext) -> Deferred<[Product]> { let deferred = Deferred<[Product]>() dispatch_async(queue) { let products = fetchProductsInContextSync(context) deferred.fill(products) } return deferred }

Slide 46

Slide 46 text

Result + Deferred: ≈> infix operator ≈> { associativity left precedence 160 } func ≈> (lhs : Deferred>, rhs : T -> Deferred>) -> Deferred>

Slide 47

Slide 47 text

Deferred> func fetchWallData() -> Deferred> func parseWallPage(data:NSData) -> Deferred> func requestWallPage () -> Deferred> { return fetchWallData() ≈> parseWallPage }

Slide 48

Slide 48 text

Deferred> let wallRequest = requestWallPage() wallRequest.upon(dispatch_get_main_queue()) { result in switch result { case .Success (let box) : //Populate collectionView case .Failure (let error) : //Show failure message } }

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

Takeways: going forward

Slide 51

Slide 51 text

⌘B > ⌘R

Slide 52

Slide 52 text

• Thinking functionally makes things easier to test - More difficult to write, specially after years of OOP Takeaways

Slide 53

Slide 53 text

Takeaways • Swift compiler is like an abusive boss

Slide 54

Slide 54 text

• If your code compiles, chances are, it works - This is true for all Swift code, but even more if you use the types mentioned earlier Takeaways

Slide 55

Slide 55 text

• Bridging to ObjC isn’t hard - It’s just boring Takeaways

Slide 56

Slide 56 text

• It’s not as hard as it looks - Taking it one step at a time helps a lot Takeaways

Slide 57

Slide 57 text

• OOP suits perfectly for UI implementations. • OOP suits fine for modeling data ‣ Functional is perfect for modeling the transformation of this data Takeaways

Slide 58

Slide 58 text

• John Gallagher - Networking with Monads • Nick Lockwood - Thoughts on Swift 2 Errors • Andy Matuschak - Controlling Complexity in Swift • Wallapop iOS Team - WallaFoundation Resources

Slide 59

Slide 59 text

No content