Fewer "guard" more flatMap
Swift's guard syntax is good, I admitted.
But it's not always the best choice in some cases.
Let's consider:
something.callback() { someOther:SomeOther? in
guard let someOther = someOther else {
return
}
functionTakeSomeOther(someOther)
}
Indeed, "optional chaining" provide us a more convenience way to achieve the same goal with fewer even cleaner code.
something.callback() { someOther:SomeOther? in
someOther.flatMap(functionTakeSomeOther)
}
Further more, we can push the edge a bit up front:
let someOptionalValue: T? = T()
class B {
init(value:T) {
...
}
}
func funcTakeT(t:T) -> U {
...
}
Then we can:
let b = someOptionalValue.flatMap(B.init)
let u = someOptionalValue.flatMap(funcTakeT)
If we don't have side effect to handle, consider to use 'flatMap' for replacing 'guard'.
Original post from my previous site: http://povoq.blogspot.com/2017/07/fewer-guard-more-flatmap.html