微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift中的Python“或”等价物?

由于 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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐