Providing a default value for an Optional in Swift?

后端 未结 4 1990
傲寒
傲寒 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条回答
  •  旧巷少年郎
    2020-11-29 18:37

    if you wrote:

    let result = optionalValue ?? 50
    

    and optionalValue != nil then result will be optional too and you will need unwrap it in future

    But you can write operator

    infix operator ??? { associativity left precedence 140 }
    
    func ???(optLeft:T?, right:T!) -> T!
    {
        if let left = optLeft
        {
            return left
        }
        else { return right}
    }
    

    Now you can:

     let result = optionalValue ??? 50
    

    And when optionalValue != nil then result will be unwraped

提交回复
热议问题