像这样的东西:
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 ?? defaultValueprint(myString)总结
以上是内存溢出为你收集整理的Swift中的Python“或”等价物?全部内容,希望文章能够帮你解决Swift中的Python“或”等价物?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)