swift - 如何满足消费类型的通用约束?
问题描述
我有一个泛型类型。我正在尝试使其成为另一种类型的属性,但不知道如何使 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
。这样做的正确方法是什么?
解决方案
MainPresenter
是通用的Store
。Store
需要在类型定义中。
你可以在它前面加上你的模块的名字,这样你就不需要使用一些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
}
}
推荐阅读
- json - 如何在 Microsoft Flow 中转义 json 中的引号?
- javascript - 尝试使用 try 和 catch 作为条件
- python - 是否可以将 HyperDriveStep 与时间序列交叉验证一起使用?
- python - 使用正则表达式忽略不完整的数据集?
- java - 如何为我要进行基准测试的函数提供随机输入?
- php - 无法连接到 gmail-imap.l.google.com,993:连接被拒绝
- python - 为什么当用户按下按钮时我的 Tkinter GUI 会冻结(仅当我使用线程时)?
- reactjs - 如何在 React-Redux 应用程序中修复 431 请求标头字段太大
- crash - .Net 进程的自动故障转储
- git - 如何关闭 GIT 凭据管理器