Search code examples
swiftoption-type

Swift: adding optionals Ints


I declare the following:

var x:Int?
var y:Int?

and I'd like a third variable z that contains the sum of x and y. Presumably, as x & y are optionals, z must also be an optional:

var z:Int? = x + y

but this gives a complier error "value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'"

If I unwrap x & y:

var z:Int? = x! + y!

I get a run-time error as x & y are nil, so can't be unwrapped.

I can achieve the desired result as follows:

var z:Int?

if let x1 = x {
    if let y1 = y {
       z = x1+y1
    }
}

but this seems a bit verbose for adding together 2 integers! Is there a better way of achieving this?


Solution

  • 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