On Mon, Oct 3, 2016, at 03:18 PM, Jordan Rose wrote: > >> On Oct 3, 2016, at 14:41, Kevin Ballard via swift-evolution <swift- >> evolut...@swift.org> wrote: >> >> On Mon, Oct 3, 2016, at 10:52 AM, Harlan Haskins via swift- >> evolution wrote: >>> Swift developers frequently use string interpolation as a >>> convenient, concise syntax for interweaving variable values with >>> strings. The interpolation machinery, however, has surprising >>> behavior in one specific case: Optional<T>. If a user puts an >>> optional value into a string interpolation segment, it will insert >>> either "Optional("value")" or "nil" in the resulting string. Neither >>> of these is particularly desirable, so we propose a warning and fix- >>> it to surface solutions to these potential mistakes. >> >> Is there any way we could instead allow Optionals but just print >> them the way we print ImplicitlyUnwrappedOptionals? That's almost >> always how I want my Optionals to work when interpolating. To be >> specific, this means for .some(x) we just print x, and for .none we >> print "nil". > We had this at one point, but we took it out because people would > forget to test the nil case. I think `?? ""` or `?? nil` really is the > best answer here.
But you can't write that, unless you're dealing specifically with an Optional<String>. If you try you'll get an error: unnamed.swift:2:19: error: binary operator '??' cannot be applied to operands of type 'Int?' and 'String' print("x: \(x ?? "nil")") ~ ^ ~~~~~ unnamed.swift:2:19: note: overloads for '??' exist with these partially matching parameter lists: (T?, @autoclosure () throws -> T), (T?, @autoclosure () thro ws -> T?) print("x: \(x ?? "nil")") ^ This leads to writing code like "… \(x.map(String.init(describing:)) ?? "nil")" which is pretty gross. -Kevin
_______________________________________________ swift-evolution mailing list swift-evolution@swift.org https://lists.swift.org/mailman/listinfo/swift-evolution