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.
1 Answer 1
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!
-
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.– Daniel T.2016年05月04日 23:27:08 +00:00Commented May 4, 2016 at 23:27
-
1I 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, butErrorType
actually has some hidden requirements. I believe it'll be more formalized in Swift 3.JHZ– JHZ2016年05月05日 00:18:17 +00:00Commented 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.JHZ– JHZ2016年05月05日 00:20:42 +00:00Commented May 5, 2016 at 0:20 -
I guess there is no contrary view...Daniel T.– Daniel T.2016年05月14日 22:43:18 +00:00Commented May 14, 2016 at 22:43