【问题标题】:var conforms a protocol which has associateTypevar 符合具有 associateType 的协议
【发布时间】:2018-06-03 10:16:18
【问题描述】:

我制定了一个包含associatedType 的协议。

public protocol HBPrerollProtocol: NSObjectProtocol {
    associatedtype HBContentType

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

我正在尝试创建一个具有符合上述协议的属性的视图。

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

但这不起作用,因为协议有associateType。错误如下:

Protocol 'HBPrerollProtocol' 只能用作通用约束,因为它具有 Self 或关联的类型要求

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

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

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

这会导致另一个错误:

属性不能被声明为开放,因为它的类型使用了内部类型

因为这些类在一个单独的模块中,所以我必须将类型设为泛型,以便可以将这些类与不同的模块一起使用。

我的任务是:

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

  2. 如果没有,我怎样才能使泛型类型T 公开或公开?

【问题讨论】:

    标签: swift generics protocols


    【解决方案1】:

    你在寻找这样的东西吗?

    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?
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-21
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      相关资源
      最近更新 更多