Wednesday 15 January 2014

Avoid consecutive "if let" declarations in Swift -



Avoid consecutive "if let" declarations in Swift -

in swift used if let declarations check if object not nil

if allow obj = optionalobj { }

but sometimes, have face consecutive if let declarations

if allow obj = optionalobj { if allow = obj.a { if allow b = a.b { // stuff } } }

i'm looking way avoid consecutive if let declarations.

i seek :

if allow obj = optionalobj && if allow = obj.a && if allow b = a.b { // stuff }

but swift compiler not allow this.

any suggestion ?

i wrote little essay on alternatives time ago: https://gist.github.com/pyrtsa/77978129090f6114e9fb

one approach not yet mentioned in other answers, kinda like, add together bunch of overloaded every functions:

func every<a, b>(a: a?, b: b?) -> (a, b)? { switch (a, b) { case allow (.some(a), .some(b)): homecoming .some((a, b)) default: homecoming .none } } func every<a, b, c>(a: a?, b: b?, c: c?) -> (a, b, c)? { switch (a, b, c) { case allow (.some(a), .some(b), .some(c)): homecoming .some((a, b, c)) default: homecoming .none } } // , on...

these can used in if let statements, case expressions, optional.map(...) chains:

// 1. var foo: foo? if allow (name, phone) = every(parsedname, parsedphone) { foo = ... } // 2. switch every(parsedname, parsedphone) { case allow (name, phone): foo = ... default: foo = nil } // 3. foo = every(parsedname, parsedphone).map{name, phone in ...}

having add together overloads every boilerplate'y has done in library once. similarly, applicative functor approach (i.e. using <^> , <*> operators), you'd need create curried functions somehow, causes bit of boilerplate somewhere too.

swift

No comments:

Post a Comment