Swift inline conditional?
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
}
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