【发布时间】:2019-02-05 14:24:12
【问题描述】:
我正在尝试使用两个相互关联的通用协议:
protocol PersistableData {}
protocol DataStore: class {
associatedtype DataType: PersistableData
func save(data: DataType, with key: String)
func retreive(from key: String) -> DataType?
}
protocol PersistentDataModel {
// Swift infers that DataType: PersistableData as DataType == DataStoreType.DataType: PersistableData
// Setting it explicitly makes the compiler fail
associatedtype DataType
associatedtype DataStoreType: DataStore where DataStoreType.DataType == DataType
}
extension String: PersistableData {}
protocol StringDataStore: DataStore {
associatedtype DataType = String
}
class Test: PersistentDataModel {
typealias DataType = String
typealias DataStoreType = StringDataStore
}
但是 Xcode 编译失败说 Type 'Test' does not conform to protocol 'PersistentDataModel' 并建议 Possibly intended match 'DataStoreType' (aka 'StringDataStore') does not conform to 'DataStore' 而 StringDataStore 被定义为符合 DataStore
我已经阅读了一些关于通用协议的好资源,包括 SO 和这个 Medium post,但我找不到问题所在。
【问题讨论】:
-
你为什么有
associatedtype DataStoreType: DataStore where DataStoreType.DataType == DataType? -
这个SO question 可能会对你有所帮助。