Tarang
Tarang

Reputation: 75955

Is it possible to do '||' (Javascript) in swift?

In javascript we can do:

var val = null;
var str = val || "ok";

Then str would be ok and not null but only if its not null-ish to begin with.

Is there a quick/short way to do this in swift? It's possible to do this:

var val:String?

if val == nil {
    val = "OK"
}

But if there's a lot of variables to do this to it becomes quite long. Is there a short/er way to do this?

Upvotes: 1

Views: 55

Answers (1)

Nate Cook
Nate Cook

Reputation: 93286

You're looking for the null coalescing operator: ??:

var val: String?
val = val ?? "OK"

Upvotes: 2

Related Questions