Swift: adding optionals Ints

Here is my take, I think it's cleaner:

let none:Int? = nil
let some:Int? = 2

func + (left: Int?, right:Int?) -> Int? {
    return left != nil ? right != nil ? left! + right! : left : right
}

println(none + none)
println(none + some)
println(some + none)
println(some + some)
println(2 + 2)

With results of:

nil
Optional(2)
Optional(2)
Optional(4)
4

The best I can think of is:

if x && y {
    z = x! + y!;
}

Since they are all Optionals... there's really no way to avoid:

  1. checking that they aren't nil
  2. Unwrapping them before you add them.

Best solution IMO:

z = x.map { x in y.map { $0 + x } }

Did you know the map operator on Optional<T>? It is very nice.

Documentation says:

If self == nil, returns nil. Otherwise, returns f(self!).

Tags:

Swift

Optional