Ashley Mills Ashley Mills - 3 months ago 8
Swift Question

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?

Answer

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.
Comments