[swift-evolution] Proposal: Deprecate optionals in string interpolation

David Sweeris davesweeris at mac.com
Wed May 18 20:33:27 CDT 2016


We could make Optional conform to CustomStringConvertible:
var description: String {
    switch self {
        case .some(let x): return "\(x)"
        case .none: return "\(Wrapped.self)?.none"
    }
}

- Dave Sweeris

> On May 18, 2016, at 15:56, Michael Peternell via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Well, I wouldn't deprecate them.
> 
> Maybe it should print something different: the value itself if it is not nil, and "nil" otherwise?
> 
> Or there may be an optional warning for this case.
> 
> Or maybe both. But not just deprecate the feature altogether. It will make people use the "!" instead in unsafe places (like "\(someOptional!)") - it's better not to crash and print something strange instead. Especially when in production.
> 
> -Michael
> 
>> Am 18.05.2016 um 20:50 schrieb Krystof Vasa via swift-evolution <swift-evolution at swift.org>:
>> 
>> The string interpolation is one of the strong sides of Swift, but also one of its weaknesses. 
>> 
>> It has happened to me more than once that I've used the interpolation with an optional by mistake and the result is then far from the expected result. 
>> 
>> This happened mostly before Swift 2.0's guard expression, but has happened since as well.
>> 
>> The user will seldomly want to really get the output "Optional(something)", but is almost always expecting just "something". I believe this should be addressed by a warning to force the user to check the expression to prevent unwanted results. If you indeed want the output of an optional, it's almost always better to use the ?? operator and supply a null value placeholder, e.g. "\(myOptional ?? "<<none>>")", or use myOptional.debugDescription - which is a valid expression that will always return a non-optional value to force the current behavior.
>> 
>> Krystof
>> 
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution


More information about the swift-evolution mailing list