Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift inline conditional?

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)") 
like image 735
Duncan Groenewald Avatar asked Oct 04 '14 03:10

Duncan Groenewald


People also ask

Does Swift have a ternary operator?

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.

What does ~= mean in Swift?

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.

What are the conditional statements available in Swift?

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.


1 Answers

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

like image 143
Mike S Avatar answered Sep 20 '22 18:09

Mike S