I have a class that uses a type, but it doesn't need to know anything about that type. In Swift, I can code this up one of two ways:

protocol Type { }

class Class {
    // use Type


class Class<Type> {
    // use Type

Right now I'm leaning toward the latter because if the client wants to use an empty protocol for the type, they can just instantiate the generic class with an empty protocol.

I'd like to get feedback about what others think.


You should use the generic type parameter in this case. Using an empty protocol will be almost equivalent to using Any (unlike Any, types would have to be manually extended to conform to Type).

Once you put something into Class, you would be losing its type information, just like if you had used Any. That type information could be useful, don't throw it away!

| improve this answer | |
  • Do you think Apple made a mistake when they created the numerous empty types that are in the Swift library? (Like ErrorType among others?) – Daniel T. May 4 '16 at 23:27
  • 1
    I dislike Swift's do/try/catch syntax for various reasons (doesn't compose well, throws away type information), and would have preferred an official version of Result instead, but ErrorType actually has some hidden requirements. I believe it'll be more formalized in Swift 3. – JHZ May 5 '16 at 0:18
  • Note that if you want to only allow types that have been explicitly conformed to an empty protocol, you can use Class<Type: Protocol> to achieve both. Result does this. – JHZ May 5 '16 at 0:20
  • I guess there is no contrary view... – Daniel T. May 14 '16 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.