Search code examples
swiftnslogoption-type

How to NSLog an Optional Int in Swift?


NSLog is still around in Swift, and offers some extras not available with println such as the timestamp, module, and thread.

However, I'm unsure how to log an optional, for example an optional Int.

Logging an unwrapped optional works fine, e.g.

if let i = myIndex 
{
   NSLog("%@ i %d", __FUNCTION__, i)
}

Attempting to log myIndex, which I would expect to be an object therefore using format specifier %@;

NSLog("%@ myIndex %@", __FUNCTION__, myIndex)

Gives build error:

Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?

How can I use NSLog - not println - to console out my Optional Int?


Solution

  • Just use the string interpolation syntax:

    let d: Int? = 5
    
    NSLog("\(d)")