[Pitch] Default values for string interpolations

With an Either type, no compiler magic is needed. See this Swift Fiddle.

extension String.StringInterpolation {
    mutating func appendInterpolation<T>(_ value: Either<T, String>) {
        let string = switch value {
            case .left(let value): String(describing: value)
            case .right(let value): value
        }
        appendLiteral(string)
    }
}

enum Either<Left, Right> {
    case left(Left)
    case right(Right)
}

func ?? <Left, Right>(lhs: Left?, rhs: @autoclosure () -> Right) -> Either<Left, Right> {
    if let lhs {
        .left(lhs)
    } else {
        .right(rhs())
    }
}

let name: String? = nil
print("Hello, \(name ?? "new friend")!")

let age: Int? = nil
print("Your age: \(age ?? "missing")")

Similarly to this use-case on the other thread, instead of using a general purpose Either, we can scope it locally to a single-purpose StringInterpolationResult enum.

1 Like