Member-only story

Apple has now added a coalescing operator:

var unwrappedValue = optionalValue ?? defaultValue

The ternary operator is your friend in this case

var unwrappedValue = optionalValue ? optionalValue! : defaultValue

You could also provide your own extension for the Optional enum:

extension Optional {
func or(defaultValue: T) -> T {
switch(self) {
case .None:
return defaultValue
case .Some(let value):
return value
}
}
}

Then you can just do:

optionalValue.or(defaultValue)

However, I recommend sticking to the ternary operator as other developers will understand that much more quickly without having to investigate the or method.

--

--

Mr.Javed Multani
Mr.Javed Multani

Written by Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer

No responses yet