简体   繁体   中英

Why is there no hybrid class-protocol type in Swift?

I'm relatively new to Swift, and one thing that has frustrated me is the inability to create a single type that represents both a class and protocol (similar to Class<Protocol> * in Objective-C). There is the protocol<Protocol1, Protocol2> operator which can create a new protocol type from multiple protocols; so my question is, why is this not possible with a class and a protocol?

I am aware that this can be accomplished using generics (eg <T: Class where T: Protocol> ). However, this seems kludgy, especially in situations where you might want to store that type in an instance variable but don't want to add generics to your class for what would would be considered an implementation detail.

I would like to better understand why this is not possible in Swift. Specifically, I am interested in how class and protocol types are implemented (or defined) and why it is not possible to combine them into a single type as a result.

What about this?

Let's declare a protocol and a class

protocol Wearable { }
class Computer { }

Then let's declare 3 classes

class AppleWatch: Computer, Wearable { }
class Mac: Computer { }
class Jeans: Wearable { }

And now a method that accepts a value that must extend Computer and conform to Wearable

func foo<T:Computer where T: Wearable>(something:T) { }

And finally let's test them:

foo(AppleWatch()) // OK
foo(Mac()) // error at compile time
foo(Jeans()) // error at compile time 

Is it what you mean?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM