本文介绍了泛型类型符合Swift中的协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能要求泛型类型的具体实例符合Swift中的协议?

例如,假设我有一个名为<$ c $的泛型C>东西< T> 。我希望 Thing< Int> 符合特定协议,但不符合 Thing< T>

解决方案

好吧,它可能不会太繁琐,而且可能已经很明显,您已经忽略了它,但是您可以创建一个特定

  class ThingOfInt:Thing< Int> SpecialIntProtocol {
// //实现一个泛型类型的实例化SpecialIntProtocol(如果它不是已经在扩展中实现的

}

或者更通用:

 类IntThing< T:IntegerType> :MyThing< T>,SpecialIntProtocol {
}


Is it possible to require that specific instantiations of generic types conform to a protocol in Swift?

For example, say I have a generic type called Thing<T>. I want Thing<Int> to conform to a certain protocol, but not Thing<T>.

解决方案

Well, it might not be too onerous, and it might be obvious enough that you've ignored it, but you could make a 'specific instantiation of a generic type' - as:

class ThingOfInt : Thing<Int>, SpecialIntProtocol {
 // implement SpecialIntProtocol (if it isn't already
 // implemented in an extension)
}

or with a bit more generality:

class IntThing<T:IntegerType> : MyThing<T>, SpecialIntProtocol {
}

这篇关于泛型类型符合Swift中的协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-16 01:42