Thursday, May 12, 2016

Compile Time vs. Run Time Type Checking in Swift

Benjamin Encz:

The dynamic type check in the above example actually works correctly. The body of the if let block is only executed for types that conform to our two expected protocols. However, we cannot convey this to the compiler. The compiler expects a concrete type (one that has a fully specified type at compile time) that conforms to HumanType and HasName. All we can offer is a dynamically verified type.


The solution of the “type erased” function that accept an Any argument isn’t really nice either; but in practice I have used similar approaches in cases where other code guarantees that the function will be called with the correct type, but there wasn’t a way of expressing that within Swift’s type system.

Update (2016-05-12): Joe Groff:

It is possible to “open” a protocol<> type into a concrete type via a protocol extension.

Comments RSS · Twitter

Leave a Comment