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
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution