Ashley Mills - 11 months ago 59

Swift Question

I declare the following:

`var x:Int?`

var y:Int?

and I'd like a third variable

`z`

`x`

`y`

`x`

`y`

`z`

`var z:Int? = x + y`

but this gives a complier error

If I unwrap

`x`

`y`

`var z:Int? = x! + y!`

I get a run-time error as

`x`

`y`

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:

- checking that they aren't
`nil`

- Unwrapping them before you add them.

Source (Stackoverflow)