简体   繁体   English

符合Swift协议的泛型类型

[英]generic type conforming to a protocol in Swift

Is it possible to require that specific instantiations of generic types conform to a protocol in Swift? 是否有可能要求泛型类型的特定实例符合Swift中的协议?

For example, say I have a generic type called Thing<T> . 例如,假设我有一个名为Thing<T>的泛型类型。 I want Thing<Int> to conform to a certain protocol, but not Thing<T> . 我希望Thing<Int>符合某个协议,但不符合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 {
}

In Swift 2.0 you can extend protocols and types Swift 2.0中,您可以扩展协议和类型

When you extend it you can add a generic where constraints. 扩展它时,可以where约束条件下添加泛型。 Only types that matches that rule will be able to use that functionality 只有符合该规则的类型才能使用该功能

Example : 示例

public struct Thing<T> {
  let x: T
}

extension Thing where T : IntegerType {
  func giveMeInt () -> T {
    return x
  }
}

let a = Thing<Int>(x: 10)
a.giveMeInt()

let b = Thing(x: 10.1)
//b.giveMeInt() // Error

This way you can add an extra functionality to Thing<Int> type 这样,您可以为Thing<Int>类型添加额外的功能

I don't know a way to conform to a protocol in the extension, but it doesn't make much sense. 我不知道在扩展中遵循协议的方法,但它没有多大意义。

Limitation: Generic where T : can be used with protocols and classes, that's why we can't specify Int there 限制:通用where T :可以与协议和类一起使用,这就是为什么我们不能在那里指定Int

You can do something like using the where keyword and pass a condition afterwords. 你可以做一些事情,比如使用where关键字并传递一个条件。 Saw this under Where Clauses section https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html#//apple_ref/doc/uid/TP40014097-CH26-XID_275 在Where子句部分下看到这一点https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html#//apple_ref/doc/uid/TP40014097-CH26-XID_275

class Thing<T : SomeProtocol where reflect(T).summary != "Int"> {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM