I'm looking for a solid, repeatable pattern for filling in an optional value. The behavior I want is "if it's nil, use this default".
I have three ways to approach it so far.
// Three approaches for using a default value when the optional is nil
// Device.location is an optional `CLLocation?`
// cfg.defaultLocation is `CLLocation`
// 1: bitwise (nice and short, requires a holding variable)
let location1: CLLocation! = Device.location ?? cfg.defaultLocation
positionMap(location1)
// 2: if let (sooooo many lines!)
if let location2 = Device.location {
positionMap(location2)
} else {
positionMap(cfg.defaultLocation)
}
// 3: re-wrap (holding var :( )
let location3: CLLocation! = Device.location
positionMap(location3 ?? cfg.defaultLocation)
You guys have a better way to do this? Comes up a lot for me.