How do I do this in Swift ?
(someboolexpression ? "Return value 1" : "Return value 2")
(no I have not read the whole manual yet... I probably missed it on page 2!)
OK so its on page 91 and the above appears to be correct. However I am trying to use this in a string like so:
println(" some string \(some expression ? "Return value 1" : "Return value 2")"
but the compiler is not happy. Any idea if this if possible?
This is as close as I have been able to get
let exists = "exists" let doesnotexist= "does not exist" println(" something \(fileExists ? exists : doesnotexist)")
Swift has a rarely used operator called the ternary operator. It works with three values at once, which is where its name comes from: it checks a condition specified in the first value, and if it's true returns the second value, but if it's false returns the third value.
Search for a value in a range Today we'll learn about a not-so-well-known operator in Swift, looking at some real-life examples: ~= . In short, we use this operator when we want to check if a range contains a certain value.
Swift if Statement The if statement evaluates condition inside the parenthesis () . If condition is evaluated to true , the code inside the body of if is executed. If condition is evaluated to false , the code inside the body of if is skipped.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With