Sometimes I find myself writing swift 2 code like this:
class Test {
var optionalInt: Int?
var nonOptionalInt: Int = 0
func test() {
if let i = optionalInt {
nonOptionalInt = i
}
// do more stuff
}
}
where the problematic part is this:
if let i = optionalInt {
nonOptionalInt = i
}
In words: if optionalInt has a value, assign it to the variable nonOptionalInt, else do nothing.
Is there an equivalent way in swift 2 to express this in a elegant single line without adding an intermediate variable with if let i?
Edit
after contemplating the first answers...
Obviously there is an equivalent way
if optionalInt != nil {
nonOptionalInt = optionalInt!
}
Ternary operators ? : are not equivalent as they may trigger a didSet which the original code does not (good if this is a intended side effect)
The most elegant answer so far appears to be
nonOptionalInt = optionalInt ?? nonOptionalInt
it may also trigger a didSet like the ternary operator and therefore is not equivalent (also good if this is intended).
I think my wish to Apple would be something like
nonOptionalInt = optionalInt ??
or
nonOptionalInt ??= optionalInt