Solution for No Optionals in Swift String Interpolation
This is probably a bad idea, but it's fun to consider (for a brief moment).
// Solution is reduced from here
/// Anything that can be unwrapped.
public protocol Unwrappable {
/// Returns the unwrapped value of the receiver.
func unwrap() -> Any?
}
extension Optional: Unwrappable {
/// Returns the unwrapped value of the `Optional`.
public func unwrap() -> Any? {
switch self {
case nil:
return nil
case let unwrappable as Unwrappable:
return unwrappable.unwrap()
case let any:
return any
}
}
}
public extension String {
/// Creates an instance containing the unwrappable's representation.
init(stringInterpolationSegment expr: Unwrappable) {
if let unwrapped = expr.unwrap() {
self.init(stringInterpolationSegment: unwrapped)
} else {
self.init("nil")!
}
}
init(stringInterpolationSegment expr: Optional<T>) {
self.init(stringInterpolationSegment: expr as Unwrappable)
}
}
/**
Force the default behavior
*/
postfix operator *
public postfix func *(optional: Optional<Any>) -> String {
if "\(optional)" == "nil" {
return "nil"
}
return "Optional(\"\(optional)\")"
}