通用函数中无法识别协议一致性



我将不胜感激我对这个问题的任何见解。我正在尝试在 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(最新的非测试版(中的一个简单的游乐场中完成。谁能看到我在这里做错了什么?

您的函数需要一个实现SettableTitle的对象,而不是一个类型。

相反,您需要执行T.Type,它将起作用:

class SomeClass {
static func dynamicMethod<T: SettableTitle>(type: T.Type, title: String) {
T.objectWithTitle(title: title)
}
}

源:在泛型中使用类型变量

最新更新