2

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
}
1
  • 2
    var value = someOptionalField ?? someDefaultValue
    – nathan
    Aug 10, 2017 at 22:43

1 Answer 1

8

Use the nil-coalescing operator:

let value = someOptionalField ?? someDefaultValue

If someOptionalField is nil, it automatically assigns value to someDefaultValue

2
  • Yep, totally forgot about that. Aug 10, 2017 at 22:43
  • Yea I mostly use this as well, or if let
    – J. Doe
    Aug 10, 2017 at 22:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.