Providing a default value for an Optional in Swift? -
the idiom dealing optionals in swift seems excessively verbose, if want provide default value in case it's nil:
if let value = optionalvalue { // 'value' } else { // same thing default value }
which involves needlessly duplicating code, or
var unwrappedvalue if let value = optionalvalue { unwrappedvalue = value } else { unwrappedvalue = defaultvalue }
which requires unwrappedvalue
not constant.
scala's option monad (which same idea swift's optional) has method getorelse
purpose:
val myvalue = optionalvalue.getorelse(defaultvalue)
am missing something? swift have compact way of doing already? or, failing that, possible define getorelse
in extension optional?
update
apple has added coalescing operator:
var unwrappedvalue = optionalvalue ?? defaultvalue
the ternary operator friend in case
var unwrappedvalue = optionalvalue ? optionalvalue! : defaultvalue
you provide own extension optional enum:
extension optional { func or(defaultvalue: t) -> t { switch(self) { case .none: return defaultvalue case .some(let value): return value } } }
then can do:
optionalvalue.or(defaultvalue)
however, recommend sticking ternary operator other developers understand more without having investigate or
method
note: started module add common helpers or
on optional
swift.
Comments
Post a Comment