How to NSLog an Optional Int in Swift?
16,816
Just use the string interpolation syntax:
let d: Int? = 5
NSLog("\(d)")
Author by
Max MacLeod
Please feel free to checkout my LinkedIn profile for contact details and app portfolio.
Updated on July 16, 2022Comments
-
Max MacLeod almost 2 years
NSLog
is still around in Swift, and offers some extras not available withprintln
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 about 9 yearswas using that however it seems to cause crashes. At least previous to beta 3. Will try it now
-
Max MacLeod about 9 yearsyeah it always compiled OK but sometimes crashed on the NSLog with interpolation
-
Dániel Nagy about 9 yearsCouldn't be that same beta crash? I did not experienced that.
-
Kirsteins about 9 yearsAs an alternative you can use:
let i: Int? = 5
NSLog("%@", toString(i))
-
Max MacLeod about 9 yearsNot seeing crashes these days with NSLog string interpolation using Xcode 6.3.1 (6D1002), so accepting answer above. Thanks @DánielNagy