加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift中的Python“或”等价物?

发布时间:2020-12-14 04:47:29 所属栏目:百科 来源:网络整理
导读:由于 Swift很酷的行为,我在 Swift中寻找一个或同等的. 像这样的东西: variable = value or default 我编码mine: func |T(a:T?,b:T) - T { if let a = a { return a } return b} 但我想知道Swift中是否存在任何默认实现? 编辑: 感谢答案,我在Swift书中找
由于 Swift很酷的行为,我在 Swift中寻找一个或同等的.

像这样的东西:

variable = value or default

我编码mine:

func |<T>(a:T?,b:T) -> T {
    if let a = a {
        return a
    }
    return b
}

但我想知道Swift中是否存在任何默认实现?

编辑:
感谢答案,我在Swift书中找到了参考:

Nil Coalescing Operator

The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value,or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

The nil coalescing operator is shorthand for the code below:

06002

The code above uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil,and to return b otherwise. The nil coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form. (07001)

解决方法

使用 ??:

var optional:String?
var defaultValue:String = "VALUE"

var myString:String = optional ?? defaultValue

print(myString)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读