[英]generic type conforming to a protocol in Swift
是否有可能要求泛型類型的特定實例符合Swift中的協議?
例如,假設我有一個名為Thing<T>
的泛型類型。 我希望Thing<Int>
符合某個協議,但不符合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 {
}
在Swift 2.0中,您可以擴展協議和類型
擴展它時,可以where
約束條件下添加泛型。 只有符合該規則的類型才能使用該功能
示例 :
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
這樣,您可以為Thing<Int>
類型添加額外的功能
我不知道在擴展中遵循協議的方法,但它沒有多大意義。
限制:通用where T :
可以與協議和類一起使用,這就是為什么我們不能在那里指定Int
你可以做一些事情,比如使用where
關鍵字並傳遞一個條件。 在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.