Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Using Logger with optionals

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)")
like image 389
iphaaw Avatar asked Oct 23 '25 18:10

iphaaw


1 Answers

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
like image 138
Martin R Avatar answered Oct 26 '25 06:10

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!