Swift内联条件?

时间:2014-10-04 03:47:27

标签: swift conditional

我如何在Swift中执行此操作?

(someboolexpression ? "Return value 1" : "Return value 2")

(不,我还没有阅读整本手册......我可能在第2页错过了它!)

好,所以它在第91页和上面似乎是正确的。但是我试图在这样的字符串中使用它:

println(" some string \(some expression ? "Return value 1" : "Return value 2")"

但编译器不满意。如果可能的话,有任何想法吗?

这和我能够得到的一样接近

let exists = "exists"
let doesnotexist= "does not exist"

println("  something \(fileExists ? exists : doesnotexist)")

9 个答案:

答案 0 :(得分:107)

如果你正在寻找单行代码,你可以将?:操作从字符串插值中拉出来,并与+连接:

let fileExists = false // for example
println("something " + (fileExists ? "exists" : "does not exist"))

输出:

  

某些东西不存在

答案 1 :(得分:21)

您可以使用 Swift 3 中引入的新 Nil-Coalescing Operator 。如果max duration of the fastest 90%someOptional

,它将返回默认值
nil

如果let someValue = someOptional ?? "" 为false,则此运算符会将someOptional分配给""

答案 2 :(得分:17)

var firstBool = true
var secondBool: Bool

firstBool == true ? (secondBool = true) : (secondBool = false)

如果在这种情况下,它将secondBool更改为firstBool。您也可以使用整数和字符串来执行此操作

答案 3 :(得分:6)

你太近了。只需要将它分配给变量:

self.automaticOption = (automaticOptionOfCar ? "Automatic" : "Manual")

编辑:

  

知道为什么同一个表达式不能嵌入字符串中吗?

你可以这样做:

let a = true
let b = 1
let c = 2

println("\(a ? 1: 2)")

答案 4 :(得分:6)

它被称为“三元运算符”。

关于@ Esqarrouth的答案,我认为更好的格式是:

斯威夫特3:

var firstBool = true
var secondBool: Bool

secondBool = firstBool ? true : false

这与:

相同
var firstBool = true
var secondBool: Bool

if (firstBool == true) {
    secondBool = true
} else {
    secondBool = false
}

答案 5 :(得分:4)

那么,

如果使用+运算符将条件与字符串连接起来,它应该可以工作。

因此,迈克是对的。

var str = "Something = " + (1 == 1 ? "Yes" : "No")

答案 6 :(得分:3)

我在项目中使用的简单解决方案

Swift 3 +

var retunString = (state == "OFF") ? "securityOn" : "securityOff"

答案 7 :(得分:0)

我像这样使用内联条件:

isFavorite函数返回一个Boolen

favoriteButton.tintColor = CoreDataManager.sharedInstance.isFavorite(placeId: place.id, type: 0) ? UIColor.white : UIColor.clear

tourOperatorsButton.isHidden = place.operators.count != 0 ? true : false

答案 8 :(得分:0)

对于多条件,这可以像这样工作

 let dataSavingTime: DataSavingTime = value == "0" ? .ThirtySecs : value == "1" ? .Timing1 : .Timing2