是否可能要求通用类型的特定实例符合Swift中的协议(protocol)?
例如,假设我有一个名为Thing<T>
的通用类型。我希望Thing<Int>
符合某个协议(protocol),而不是Thing<T>
。
最佳答案
好吧,它可能不会太繁琐,并且可能已经很明显地使您忽略了它,但是您可以对“泛型类型进行特定的实例化”-如:
class ThingOfInt : Thing<Int>, SpecialIntProtocol {
// implement SpecialIntProtocol (if it isn't already
// implemented in an extension)
}
或更笼统:
class IntThing<T:IntegerType> : MyThing<T>, SpecialIntProtocol {
}