Swift中的Python“或”等价物?

Swift中的Python“或”等价物?,第1张

概述由于 Swift很酷的行为,我在 Swift中寻找一个或同等的. 像这样的东西: variable = value or default 我编码mine: func |<T>(a:T?, b:T) -> T { if let a = a { return a } return b} 但我想知道Swift中是否存在任何默认实现? 编辑: 感谢答案,我在Swi 由于 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 ?? defaultValueprint(myString)
总结

以上是内存溢出为你收集整理的Swift中的Python“或”等价物?全部内容,希望文章能够帮你解决Swift中的Python“或”等价物?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1009581.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存