像这样的东西:
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 valueb
ifa
is nil. The expressiona
is always of an optional type. The expressionb
must match the type that is stored insidea
.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 insidea
whena
is not nil,and to returnb
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] 举报,一经查实,本站将立刻删除。