3

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
}

or

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.

asked May 2, 2016 at 11:29

1 Answer 1

3

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!

answered May 2, 2016 at 17:48
4
  • Do you think Apple made a mistake when they created the numerous empty types that are in the Swift library? (Like ErrorType among others?) Commented May 4, 2016 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. Commented May 5, 2016 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. Commented May 5, 2016 at 0:20
  • I guess there is no contrary view... Commented May 14, 2016 at 22:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.