[英]Protocol conformance not recognized in generic function
I would appreciate any insight on this issue I'm having. 我很感激我对这个问题的任何见解。 I'm trying to create a generic function in Swift that accepts any type that conforms to a specific protocol.
我正在尝试在Swift中创建一个通用函数,它接受任何符合特定协议的类型。 However, when I pass a conforming type into this method, I get a compiler error saying the class doesn't conform.
但是,当我将一致符合类型传递给此方法时,我收到编译器错误,指出该类不符合。
Here's my protocol: 这是我的协议:
protocol SettableTitle {
static func objectWithTitle(title: String)
}
And here's a class I've made that conforms to this protocol: 这是我制作的符合此协议的类:
class Foo: SettableTitle {
static func objectWithTitle(title: String) {
// Implementation
}
}
Finally, here's my generic function that lives in a different class: 最后,这是我的通用函数,它位于不同的类中:
class SomeClass {
static func dynamicMethod<T: SettableTitle>(type: T, title: String) {
T.objectWithTitle(title: title)
}
}
Now, when I invoke the method like this: 现在,当我调用这样的方法时:
SomeClass.dynamicMethod(type: Foo.self, title: "Title string!")
I get the following compiler error: error: argument type 'Foo.Type' does not conform to expected type 'SettableTitle' 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!")
I can't understand why this would happen when the class Foo
declares and implements SettableTitle
conformance. 我无法理解为什么当类
Foo
声明并实现SettableTitle
一致性时会发生这种情况。
All this is in a simple playground in Xcode 8.3 (latest non-beta). 所有这些都在Xcode 8.3(最新的非beta版)的简单操场中。 Can anyone see anything I'm doing wrong here?
谁能看到我在这里做错了什么?
Your function is expecting an object that implements SettableTitle
, not a type. 您的函数期望一个实现
SettableTitle
的对象,而不是一个类型。
Instead, you need to do T.Type
, and it will work: 相反,你需要做
T.Type
,它会工作:
class SomeClass {
static func dynamicMethod<T: SettableTitle>(type: T.Type, title: String) {
T.objectWithTitle(title: title)
}
}
Source: Using a Type Variable in a Generic 来源: 在通用中使用类型变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.