快速内联条件?

我在斯威夫特要怎么做?

(someboolexpression ? "Return value 1" : "Return value 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)")
98250 次浏览

You were oh so close. Just needed to assign it to a variable:

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

Edit:

Any idea why that same expression can't be embedded in a string?

You can do that:

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


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

If you're looking for a one-liner to do that, you can pull the ?: operation out of the string interpolation and concatenate with + instead:

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

Outputs:

something does not exist

Well,

If you concatenate the conditional with the string using the + operator, it should work.

Therefore, Mike is correct.

var str = "Something = " + (1 == 1 ? "Yes" : "No")
var firstBool = true
var secondBool: Bool


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

If in this case, it changes the secondBool to whatever the firstBool is. You can do this with integers and strings too

You can use the new Nil-Coalescing Operator, introduced in Swift 3. It will return default value if someOptional is nil.

let someValue = someOptional ?? ""

Here, if someOptional is nil, this operator will assign "" to someValue.

It is called a "ternary operator".

With regards to @Esqarrouth's answer, I think a better format would be:

Swift 3:

var firstBool = true
var secondBool: Bool


secondBool = firstBool ? true : false

This is the same as:

var firstBool = true
var secondBool: Bool


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

simple solution i used in my projects

Swift 3+

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

I have use inline conditional like this :

isFavorite function returns a Boolen

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

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

For Multiple Condition this can work like this

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

One line condition without if and ternary operator

let value = "any"
// set newValue as true when value is "any"
let newValue = value == "any"
print(newValue)
//answer: true