Search code examples
swiftswift3

Best way to conditionally assign variable a value in swift


I often encounter a scenario in swift where if an optional is not nil I wish to assign it to a var, otherwise make the var a default value. I wish to then keep the result in the outer most scope of the implementation.

var value:String
if let temp = someOptionalField {
    value = temp
} else {
    value = someDefaultValue
}

The above statement seems excessive for swift since "temp" is fairly worthless. On the other hand, making the if statement like below also seems not "swifty" since getting 'someDefaultField' could be an expensive process

var value:String
if someOptionalField != nil {
    value = someOptionalField!
} else {
    value = someDefaultValue
}

What is the swiftiest way to get a conditional variable or assign it to a default value while keeping the end result in the outermost scope? Sometimes I would use the below statement but I feel using '== nil' is not taking advantage of swift optional design

var value:String? = someOptionalField
if value == nil {
    value = someDefaultValue
}

Solution

  • Use the nil-coalescing operator:

    let value = someOptionalField ?? someDefaultValue
    

    If someOptionalField is nil, it automatically assigns value to someDefaultValue