Swift: adding optionals Ints -


i declare following:

var x:int? var y:int? 

and i'd third variable z contains sum of x , y. presumably, x & y optionals, z must optional:

var z:int? = x + y 

but gives complier error "value of optional type 'int?' not unwrapped; did mean use '!' or '?'"

if unwrap x & y:

var z:int? = x! + y! 

i run-time error x & y nil, can't unwrapped.

i can achieve desired result follows:

var z:int?  if let x1 = x {     if let y1 = y {        z = x1+y1     } } 

but seems bit verbose adding 2 integers! there better way of achieving this?

here take, 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 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -