ios - 未隐式定义关联类型的通用协议(protocol)

标签 ios swift generics protocols associated-types

我试图隐式定义关联类型,但出现错误:

'RowProtocol' is ambiguous for type lookup in this context

protocol RowProtocol {
    associatedtype T
    var cellClass: T.Type { get }
    init(cellClass: T.Type)
}

struct Row: RowProtocol {
    let cellClass: T.Type
    init(cellClass: T.Type) {
        self.cellClass = cellClass
    }
}

然后您可以使用以下方式初始化它:

let implicitRow = Row(cellClass: Cell.self)

我怎样才能做到这一点?

最佳答案

遵守 RowProtocol 需要将关联类型 T 映射到具体类型,而 Row 不会执行此操作。我假设您还想使 Row 通用,这就是为什么您没有从协议(protocol)中为 T 指定类型别名。

解决方案是使 Row 也通用:

struct Row<T>: RowProtocol {
    let cellClass: T.Type
    init(cellClass: T.Type) {
        self.cellClass = cellClass
    }
}

现在编译器很高兴,因为它有一个具体类型要传递给 RowProtocol。请记住,对于编译器来说,Row 中的 TRowProtocol 中的 T 不同,后者是协议(protocol)要求,而第一个是通用的。

// exactly the same struct, but with different name for the generic argument.
struct Row<U>: RowProtocol {
    let cellClass: U.Type
    init(cellClass: U.Type) {
        self.cellClass = cellClass
    }
}

关于ios - 未隐式定义关联类型的通用协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52086370/

相关文章:

ios - 使用 AVAudioPlayer 播放多种声音(一一播放)

ios - 堆栈 View 中控件的辅助功能

c++ - 在 main() 中为通用模板类选择数据类型

ios - 在 UIButton/UITableViewCell/UICollectionViewCell 选择上禁用 VoiceOver

iphone - 使用 __weak 属性将参数传递给 block 会导致内存泄漏吗?

ios - 电话 : links 的 WKWebView 问题

ios - 在 Swift 3 中以编程方式转到另一个 View

java - 指定 ArrayList 的类型

c# - 将类型作为属性参数传递

JavaScript 显示相同的键码