2

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)")

3 Answers 3

3

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
1

I would handle it directly in the log call

var myOptional: String?
...
logger.log ("MyOptional is \(myOptional ?? "")")

or perhaps clearer

logger.log ("MyOptional is \(myOptional ?? "<nil>")")
0

Optionally (:D), just write an extension for the Optional type for CustomStringConvertible conformance:

extension Optional: CustomStringConvertible {
    public var description: String {
        return self.debugDescription
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.