[英]Ternary Conditional Operator for nil/not nil
I can use the ternary conditional operator for an if {} else {}
statement like this: a ? x : y
我可以使用三元条件运算符来表示
if {} else {}
语句: a ? x : y
a ? x : y
, or question ? answer1 : answer2
a ? x : y
,还是question ? answer1 : answer2
question ? answer1 : answer2
. question ? answer1 : answer2
。
Is it possible to use this format to check if, instead of whether a
is true
or false
, a == nil
or a != nil
? 是否可以使用此格式来检查是否
a == nil
或者a != nil
,而不是a
是true
还是false
?
UPDATE: This was arguably the biggest brain fart of my career. 更新:这可以说是我职业生涯中最大的脑屁。
You can do this: 你可以这样做:
(a == nil) ? x : y
(Parentheses are not required but may make the code clearer.) (括号不是必需的,但可以使代码更清晰。)
You can do this if you want something more confusing: 如果你想要更混乱的话,你可以这样做:
a.map { _ in x } ?? y
a != nil ? a! : b
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.
上面的代码使用三元条件运算符和强制解包(a!)来访问包含在a不是nil时的值,否则返回b。 The nil coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.
nil合并运算符提供了一种更简洁的方式来以简洁易读的形式封装此条件检查和展开。
example : 例如:
let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"
Reference : Apple documentation 参考: Apple文档
You can use ternary operator as long as your statement returns boolean value. 只要语句返回布尔值,就可以使用三元运算符。 Here, a == nil or a != nil returns boolean value so 'Yes' you can use it.
这里,a == nil或者!= nil返回布尔值,所以'是'你可以使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.