三元条件运算符为零/不为零

chi*_*uda 3 ios swift

我可以使用三元条件运算符来if {} else {}表示这样的语句:a ? x : y,或question ? answer1 : answer2.

是否有可能使用这种格式来检查,而不是无论atrue还是false,a == nil还是a != nil


更新:这可以说是我职业生涯中最大的脑屁.

rob*_*off 8

你可以这样做:

(a == nil) ? x : y
Run Code Online (Sandbox Code Playgroud)

(括号不是必需的,但可以使代码更清晰.)

如果你想要更混乱的话,你可以这样做:

a.map { _ in x } ?? y
Run Code Online (Sandbox Code Playgroud)


Lio*_*ion 5

  a != nil ? a! : b
Run Code Online (Sandbox Code Playgroud)

上面的代码使用三元条件运算符和强制展开 (a!) 来在 a 不为 nil 时访问包装在 a 内的值,否则返回 b。nil 合并运算符提供了一种更优雅的方式,以简洁易读的形式封装这种条件检查和展开。

例子 :

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"
Run Code Online (Sandbox Code Playgroud)

参考:苹果文档