I love the idea of protocol oriented programming.  So far, I’ve used it in a limited way.  But, while branching out I ran in to this case that has so far forced me to use more boiler plate code than I think I should (guard statements and casting of properties)

I’m looking to understand why the type system doesn’t simply recognize that a property type conforms to a protocol, and this should allow the class to conform to a protocol.  I know.  That made no sense.

But, this will.  Here are 2 protocols.


Take a look at how I use the protocols in the objects below.

In SomeClass,  I want to declare the property someProperty as type SomeStruct.  SomeStruct conforms to ProtocolReqiuringSomePropertyType.  I would expect the type system to recognize this.  That should satisfy the class conformance to ProtocolUsingPropertyOfOtherProtocolType.

But, the type system is forcing me to declare someProperty as ProtocolReqiuringSomePropertyType. And that means I need to case the property to a type SomeStruct each time I want to access the property defined in the struct.

Am I missing a way to do this that doesn’t require casting SomeStruct each time?


Thank you to Ash Furrow (‏@ashfurrow) for the work around. It’s not my ideal for how swift would handle it, but it gets the job done.

note: I still had to cast the computed property to the backing property to compile. But, at least this is only in a single location and not everytime I want to refer to someProperty.

Download Playground

Update Too

There is nothing like a good sleep and a long drive to let the mind wander. In this case, my mind wandered to another weak spot of my swift knowledge.  Generics, AssociatedTypes and the where clause.  This compiles and looks much better.

Download Playground


1 comment

  1. Comment by Kevil Tuan

    Kevil Tuan Reply September 28, 2018 at 2:47 pm

    Thank you for sharing download bee talk

Leave a reply

Your email address will not be published. Required fields are marked *

Go top