[swift-evolution] throw expressions in ternary operators

Krzysztof Siejkowski krzysztof at siejkowski.net
Mon May 2 07:58:15 CDT 2016


But this causes a compilation error. Don’t you think the ternary operator should allow an expression that throws on the right hand side?
For one, ?? is not a ternary operator, ?: is. But I guess it’s just a misspelling. 

Anyway, there’re the throwing versions of the ?? operator:

public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T) rethrows -> T
public func ??<T>(optional: T?, @autoclosure defaultValue: () throws -> T?) rethrows -> T?

They’re taking the throwing autoclosure as second parameter. You cannot pass `throw Error.InvalidFormat` directly, because it’s type is not resolved to `() -> throws Int` by compiler. Nos sure if it’s a bug or a feature. In either case, you can work around it by wrapping throw in closure:

let age = try dictionary["age"].flatMap { elem in
    try elem as? Int ?? { throw Error() }()
}

You can also simplify it using a throwing function, possibly from the Error enum:

enum Error : ErrorType {
    case invalidFormat
    static func throwInvalidFormat<T>() throws -> T {
        throw Error.invalidFormat
    }
}

let age = try dictionary["age"].flatMap { elem in
    try elem as? Int ?? Error.throwInvalidFormat()
}

Cheers,
Krzysztof




David.
_______________________________________________
swift-evolution mailing list
swift-evolution at swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160502/0503350a/attachment.html>


More information about the swift-evolution mailing list