Since beta 8.3, zillions warnings \"String interpolation produces a debug description for an optional value; did you mean to make this explicit?\" appeared in my code.
See Ole Begeman's fix for this. I love it. It creates a ???
operator which you can then use like this:
var someValue: Int? = 5
print("The value is \(someValue ??? "unknown")")
// → "The value is 5"
someValue = nil
print("The value is \(someValue ??? "unknown")")
// → "The value is unknown"
Two easier ways of dealing with this issue.
Option 1:
The first would be by "force-unwrapping" the value you would like to return using a bang (!)
var someValue: Int? = 5
print(someValue!)
Output:
5
Option 2:
The other way, which could be the better way - is to "safely-unwrap" the value you want returned.
var someValue: Int? = 5
if let newValue = someValue {
print(newValue)
}
Output:
5
Would recommend to go with option 2.
Tip: Avoid force unwrapping (!) where possible as we are not sure if we will always have the value to be unwrapped.
Create an interpolation method that accepts an optional generic Type with an unnamed parameter. All your annoying warnings will magically disappear.
extension DefaultStringInterpolation {
mutating func appendInterpolation<T>(_ optional: T?) {
appendInterpolation(String(describing: optional))
}
}
seems using String(describing:optional) is simplest.
default value ?? makes no sense for non-Strings e.g Int.
If Int is nil then you want the log to show 'nil' not default to another Int e.g. 0.
Some playground code to test:
var optionalString : String? = nil
var optionalInt : Int? = nil
var description_ = ""
description_ = description_ + "optionalString: \(String(describing: optionalString))\r"
description_ = description_ + " optionalInt: \(String(describing: optionalInt))\r"
print(description_)
Output
optionalString: nil
optionalInt: nil
Double click on the yellow triangle displayed on line containing this warning. This will show FixIt with two solutions.
Use String(describing:)
to silence this warning :
Using this it will become String(describing:<Variable>)
Eg. : String(describing: employeeName)
Provide a default value
to avoid this warning :
Using this it will become (<Variable> ?? default value)
Eg.: employeeName ?? “Anonymous” as! String
My solution is making an extension
which unwrap Optional
object to Any
.
When you log the object or print it out, you can see the actual object
or <nil>⭕️
(combination from text and visual character). It's useful to look at, especially in the console log.
extension Optional {
var logable: Any {
switch self {
case .none:
return "<nil>|⭕️"
case let .some(value):
return value
}
}
}
// sample
var x: Int?
print("Logging optional without warning: \(x.logable)")
// → Logging optional without warning: <nil>|⭕️