I have watched through the WWDC 2020 and thought I would switch my code to use the new Logger syntax.
I often want to print the value of optional variables which I can do with the simple print command. If I try this with the new Logger commands I get a "Cannot convert value of type 'String?' to expected argument type 'NSObject'" error. What is the recommended way of doing this with Logger?
import os
let logger = Logger(subsystem: "com.example.Fruta", category: "giftcards")
let myOptional: String?
logger.log ("MyOptional is \(myOptional)")
The reason for the (somewhat obfuscated) compiler error is that Logger requires that the interpolated types conform to the CustomStringConvertible protocol, and that is not the case for Optional.
Depending on the desired output you can explicitly convert the optional to a string:
logger.log ("MyOptional is \(String(describing: myOptional))")
// Equivalently:
logger.log ("MyOptional is \(myOptional.debugDescription)")
which produces log lines like
MyOptional is nil
MyOptional is Optional("abc")
or use nil-coalescing to provide a default value:
logger.log ("MyOptional is \(myOptional ?? "<undefined>")")
which produces log lines like
MyOptional is <undefined>
MyOptional is abc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With