【问题标题】:Protocol conformance not recognized in generic function通用功能中无法识别协议一致性
【发布时间】:2017-07-21 00:54:24
【问题描述】:

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

【问题讨论】:

    标签: swift generics protocols


    【解决方案1】:

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

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

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

    来源:Using a Type Variable in a Generic

    【讨论】:

    • 这成功了!我想我应该重新阅读有关泛型的章节。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 2022-10-04
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多