swiftoptional-variables

Working with optionals in Swift programming language


As far as I know the recommended way to use optionals (Int in this example) is the following:

var one:Int?

if var maybe = one {
  println(maybe)
}

Is it possible to use a shorter way to do something like the following?

var one:Int?
var two:Int?
var three:Int?

var result1 = one + two + three // error because not using !
var result2 = one! + two! + three! // error because they all are nil

Update

To be more clear about what I'm trying to do: I have the following optionals

var one:Int?
var two:Int?
var three:Int?

I don't know if either one or two or three are nil or not. If they are nil, I wan't them to be ignored in the addition. If they have a value, I wan't them to be added.

If I have to use the recommended way I know, it would look something like this: (unnested)

var result = 0

if var maybe = one {
  result += maybe
}
if var maybe = two {
  result += maybe
}
if var maybe = three {
  result += maybe
}

Is there a shorter way to do this?


Solution

  • Quick note - if let is preferred for optional binding - let should always be used where possible.

    Perhaps Optionals aren't a good choice for this situation. Why not make them standard Ints with a default value of 0? Then any manipulation becomes trivial and you can worry about handling None values at the point of assignment, rather than when you're working on the values?

    However, if you really want to do this then a tidier option is to put the Optionals into an Array and use reduce on it:

        let sum = [one,two,three,four,five].reduce(0) {
            if ($1) {
                return $0 + $1!
            }
            return $0
        }