Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: adding optionals Ints

Tags:

swift

optional

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?

like image 429
Ashley Mills Avatar asked Jun 27 '14 13:06

Ashley Mills


1 Answers

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
like image 183
Chris Conover Avatar answered Oct 06 '22 01:10

Chris Conover