[swift-users] Casting tuples to protocols always fails (and the compiler should know)

Joe Groff jgroff at apple.com
Mon Oct 10 12:10:30 CDT 2016

> On Oct 10, 2016, at 8:20 AM, Sebastian Hagedorn via swift-users <swift-users at swift.org> wrote:
> We encountered a very surprising behaviour in one of our apps, and believe it’s a bug/missing warning in the Swift compilter, but it would be great if someone could confirm we’re not missing a piece before I file a bug report.
> This snippet reproduces the issue:
> protocol MyProto {
>    var title: String? { get }
> }
> let tuple = (x: 100, y: 100)
> // Results in a warning as expected: Cast always fails
> let castedTupleToInt = tuple as? Int
> // No warning, although cast will always fail
> let castedTuple = tuple as? MyProto
> The way I see it, it should be pretty easy for the compiler to detect that casting a tuple to a protocol always fails, since there’s no way for a tuple to conform to a protocol.
> We came across the bug when we refactored a method to return a tuple instead of a protocol type, and thought the compiler would make us aware of all the call sites that need to adopt the the refactored return type. However, wherever we casted the return type, no warning was raised and the code just silently returned early because the cast always fails at runtime (as it should, of course).

In general, we can't say that a cast to protocol type always fails, since some other module in your program could extend the type to conform to the protocol. Although tuples aren't allowed to conform to protocols today, that's not a fundamental limitation we intend to live with forever.


More information about the swift-users mailing list