[swift-evolution] [Proposal] Typed throws

Anton Zhilin antonyzhilin at gmail.com
Wed Feb 22 12:27:32 CST 2017


As a follow-up, here is code that you can test now. It demonstrates the
same, but with normal function result.

func createArbitrary<T>(usingGenerator f: () -> (T)) -> T {
    let any: Any = 42 as Any
    if Int.self is T.Type {
        let t = any as! T
        return t
    }
    return f()
}
print(createArbitrary(usingGenerator: { return 5 }))  //=> 42

And yes, nobody should do these tricks in production code :P

2017-02-22 21:15 GMT+03:00 Anton Zhilin <antonyzhilin at gmail.com>:

I understand how parametric polymorphism works *in Haskell*. But we talk
> about Swift, and there *is* a way to get an instance of E. I’ll explain
> it another way:
>
> func bypassRethrows<E: Error>(_ f: () throws(E) -> ()) throws(E) {
>     let error: Error = MyError()  // create an instance of `MyError`
>     if MyError.self is E.Type {   // in case `E` happens to be `MyError`
>         let e: E = error as! E    // then we've actually created an instance of `E`, and we can downcast safely
>         throw e                   // voila, acquired an instance of `E`
>     }
> }
> let f: () throws MyError -> () = { }
> try bypassRethrows(f)             // actually throws `MyError`, without ever calling `f`
>
> What line here seems impossible?
>
​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170222/f79fb5cd/attachment.html>


More information about the swift-evolution mailing list