user443854
user443854

Reputation: 7455

How to print optional value in Swift?

What's the best way to NSLog an optional value? This is the best I could think of:

var s:String? = nil
NSLog("s:%@", s ?? "<nil>")

Upvotes: 1

Views: 561

Answers (2)

Airspeed Velocity
Airspeed Velocity

Reputation: 40965

Your way works if you don't want to indicate it was an optional value in case of a value being present. But for logging, it's probably best to indicate the optionality since otherwise may lead to confusion. toString will keep the indicator:

NSLog("%@", toString(s))  // either nil, or Optional("blah")

Upvotes: 2

Marat Saytakov
Marat Saytakov

Reputation: 393

Something like this:

println(s ?? "(nil)")

Upvotes: 1

Related Questions