swift - var 符合具有 associateType 的协议(protocol)

标签 swift generics protocols

我制定了一个具有associatedType 的协议(protocol)。

public protocol HBPrerollProtocol: NSObjectProtocol {
    associatedtype HBContentType

    func set(content: HBContentType, startImmediately: Bool) // set configuration and begin
}

我正在尝试创建一个具有符合上述协议(protocol)的属性的 View 。

open class HBPrerollPlayerView: HBPlayerView {
    open var preroll: HBPrerollProtocol?
}

但是这不起作用,因为该协议(protocol)具有 associateType。错误如下:

Protocol 'HBPrerollProtocol' can only be used as a generic constraint because it has Self or associated type requirements

所以我尝试制作一个符合 HBPrerollProtocol 的 View ,并使 var 就是这个 View 。

class HBPrerollView<T>: UIView, HBPrerollProtocol {
    typealias HBContentType = T
    func set(content: HBContentType, startImmediately: Bool) { }
}

open class HBPrerollPlayerView<T>: HBPlayerView {
    open var preroll: HBPrerollView<T>?
}

这会导致不同的错误:

Property cannot be declared open because its type uses an internal type

因为这些类在一个单独的模块中,所以我必须使类型通用,这样我就可以在不同的模块中使用这些类。

我的问题是:

  1. 有没有办法让 var 符合具有 associatedType 的协议(protocol)?

  2. 如果不是,我怎样才能使泛型类型 T 开放或公开?

最佳答案

你在找这样的东西吗?

public protocol HBPrerollProtocol: NSObjectProtocol {
    associatedtype HBContentType

    func set(content: HBContentType, startImmediately: Bool) // set configuration and begin
}

open class HBPrerollPlayerView<T: HBPrerollProtocol>: HBPlayerView {
    open var preroll: T?
}

关于swift - var 符合具有 associateType 的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47913053/

相关文章:

swift - 通用完成作为非通用通过

swift - 类型转换与 swift 中的通用协议(protocol)冲突?

ios - Swift - 解析 - 检查用户名是否被占用

uitableview - 单元格更改应用于多个单元格

ios - 有什么方法可以为重复的 UI 元素(例如 UITableViewCells)设置手势识别器吗?

ios - 使用 UITapGestureRecognizer 检测 UITableViewCell 内 UILabel 的点击事件

java - 如何在没有原始类型的情况下使用泛型类型参数编写 Lambda

c# - C# 中更复杂的扩展泛型

scala - 如何对泛型类型参数进行模式匹配?

swift - 无法分配给类型的不可变表达式...但使用协议(protocol)