首页 > 解决方案 > 如何满足消费类型的通用约束?

问题描述

我有一个泛型类型。我正在尝试使其成为另一种类型的属性,但不知道如何使 typealias 满足泛型类型。

这是我正在尝试做的事情:

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。这样做的正确方法是什么?

标签: swiftgenerics

解决方案


MainPresenter是通用的StoreStore需要在类型定义中。

你可以在它前面加上你的模块的名字,这样你就不需要使用一些Type后缀了。(Type是旧约定。人们现在在必要时使用Protocol,因为无法使用阴影。)

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

推荐阅读