如何满足使用类型的一般约束?

时间:2020-05-11 00:18:45

标签: swift generics

我有一个带有通用类型的类型。我正在尝试使它成为另一种类型的属性,但不知道如何使类型别名实现通用类型。

这就是我想要做的:

protocol StoreType: AnyObject {
    associatedtype State: StateType
    func send(_ action: State.Action)
}

struct MainPresenter {
    typealias Store = StoreType where Store.State == MainState

    private let store: Store

    init(store: Store) {
        self.store = store
    }
}

这给了我'where' clause cannot be attached to a non-generic declaration的编译错误。正确的方法是什么?

1 个答案:

答案 0 :(得分:1)

MainPresenterStore通用。 Store必须在类型定义中。

您可以为其加上模块名称的前缀,因此无需使用某些Type后缀。 (Type是旧约定。use Protocol now是必要的人,因为不可能进行阴影处理。)

protocol Store: AnyObject {
  associatedtype State: Module.State
  func send(_ action: State.Action)
}

struct MainPresenter<Store: Module.Store> where Store.State == MainState {
  private let store: Store

  init(store: Store) {
    self.store = store
  }
}