How to NSLog an Optional Int in Swift?

16,816

Just use the string interpolation syntax:

let d: Int? = 5

NSLog("\(d)")
Share:
16,816
Max MacLeod
Author by

Max MacLeod

Please feel free to checkout my LinkedIn profile for contact details and app portfolio.

Updated on July 16, 2022

Comments

  • Max MacLeod
    Max MacLeod almost 2 years

    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?

  • Max MacLeod
    Max MacLeod about 9 years
    was using that however it seems to cause crashes. At least previous to beta 3. Will try it now
  • Max MacLeod
    Max MacLeod about 9 years
    yeah it always compiled OK but sometimes crashed on the NSLog with interpolation
  • Dániel Nagy
    Dániel Nagy about 9 years
    Couldn't be that same beta crash? I did not experienced that.
  • Kirsteins
    Kirsteins about 9 years
    As an alternative you can use: let i: Int? = 5 NSLog("%@", toString(i))
  • Max MacLeod
    Max MacLeod about 9 years
    Not seeing crashes these days with NSLog string interpolation using Xcode 6.3.1 (6D1002), so accepting answer above. Thanks @DánielNagy