Swift inline conditional?

Duncan Groenewald picture Duncan Groenewald · Oct 4, 2014 · Viewed 76.9k times · Source

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)")

Answer

Mike S picture Mike S · Oct 4, 2014

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