![](/img/trans.png)
[英]How to implement conditional conformance of a generic to a protocol in a function?
[英]Protocol conformance not recognized in generic function
我很感激我對這個問題的任何見解。 我正在嘗試在Swift中創建一個通用函數,它接受任何符合特定協議的類型。 但是,當我將一致符合類型傳遞給此方法時,我收到編譯器錯誤,指出該類不符合。
這是我的協議:
protocol SettableTitle {
static func objectWithTitle(title: String)
}
這是我制作的符合此協議的類:
class Foo: SettableTitle {
static func objectWithTitle(title: String) {
// Implementation
}
}
最后,這是我的通用函數,它位於不同的類中:
class SomeClass {
static func dynamicMethod<T: SettableTitle>(type: T, title: String) {
T.objectWithTitle(title: title)
}
}
現在,當我調用這樣的方法時:
SomeClass.dynamicMethod(type: Foo.self, title: "Title string!")
我得到以下編譯器錯誤: error: argument type 'Foo.Type' does not conform to expected type 'SettableTitle' SomeClass.dynamicMethod(type: Foo.self, title: "Title string!")
我無法理解為什么當類Foo
聲明並實現SettableTitle
一致性時會發生這種情況。
所有這些都在Xcode 8.3(最新的非beta版)的簡單操場中。 誰能看到我在這里做錯了什么?
您的函數期望一個實現SettableTitle
的對象,而不是一個類型。
相反,你需要做T.Type
,它會工作:
class SomeClass {
static func dynamicMethod<T: SettableTitle>(type: T.Type, title: String) {
T.objectWithTitle(title: title)
}
}
來源: 在通用中使用類型變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.