Providing a default value for an Optional in Swift?

后端 未结 4 1994
傲寒
傲寒 2020-11-29 17:57

The idiom for dealing with optionals in Swift seems excessively verbose, if all you want to do is provide a default value in the case where it\'s nil:

if let         


        
4条回答
  •  旧时难觅i
    2020-11-29 19:00

    As of Aug 2014 Swift has coalescing operator (??) that allows that. For example, for an optional String myOptional you could write:

    result = myOptional ?? "n/a"
    

提交回复
热议问题