94

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)")
Duncan Groenewald
  • 8,496
  • 6
  • 41
  • 76
  • It's probably an oversight in the grammar, and you might want to file a bug on it. I haven't checked the grammar for this, but it could be worth noting that it doesn't like escaped literals, only variables. Ie. you cannot do this: println("hello \\("world")"), but you can do this: let world = "world"; println("hello \\(world)"), as you noted. Summed up, it seems to want a variable and not an expression. – Chris Conover Oct 04 '14 at 05:37
  • I'll do that, cheers. In the meantime I'll accept @MikeS answer as the best option for now – Duncan Groenewald Oct 04 '14 at 12:52
  • you need a space after `let doesnotexist` or an preprocessor error will occur and make sure you have declared `let fileExists: Bool` some where before the `println` statement which should actually be `print` as of Swift 2.0. Otherwise I tried your code it works just fine – rolling_codes Aug 13 '16 at 15:42

10 Answers10

155

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

Mike S
  • 41,895
  • 11
  • 89
  • 84
  • why is this not compiling to me? ` let answer = (enterName_text == nil)? "" : enterName_text.text! ` – Elad Benda Feb 13 '16 at 10:55
  • @EladBenda this would be better not as a comment, but as a separate question with details on what enterName_text is and the error you're getting. Best guess though is that you really want: if let answer = enterName_text?.text { ... } – Mike S Feb 13 '16 at 16:15
  • 1
    When I first tried this ternary operator, I thought it did not work in Swift. Looked here and found this answer. The problem (coming from a C/C++ background) was not putting a space between the '?' and the first argument. The '?' is treated specially in Swift for optional values and the space character makes it clear that it is really a ternary operator. – Jeff Muir May 04 '17 at 01:24
32

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.

Shemetz
  • 109
  • 1
  • 9
Vitalii Gozhenko
  • 9,220
  • 2
  • 48
  • 66
21
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

Esqarrouth
  • 38,543
  • 21
  • 161
  • 168
11

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
}
Ray Tso
  • 566
  • 9
  • 17
9

simple solution i used in my projects

Swift 3+

var retunString = (state == "OFF") ? "securityOn" : "securityOff"
Sathya Baman
  • 3,424
  • 7
  • 44
  • 77
7

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)")
Félix Saparelli
  • 8,424
  • 6
  • 52
  • 67
Steve Rosenberg
  • 19,348
  • 7
  • 46
  • 53
6

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")
Tanmay Bakshi
  • 61
  • 1
  • 2
5

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

Sergio Trejo
  • 632
  • 8
  • 23
1

For Multiple Condition this can work like this

 let dataSavingTime: DataSavingTime = value == "0" ? .ThirtySecs : value == "1" ? .Timing1 : .Timing2
Lalit Pratap
  • 119
  • 1
  • 11
-1

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