gpt4 book ai didi

swift - 如何在 Swift 中处理多个泛型协议(protocol)?

转载 作者:行者123 更新时间:2023-11-28 11:38:00 25 4
gpt4 key购买 nike

我正在尝试使用两个相互关联的通用协议(protocol):

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到 'DataStore'StringDataStore 被定义为符合 DataStore

我已经阅读了一些关于通用协议(protocol)的好资源,包括 SO还有这个Medium post ,但我找不到问题出在哪里。

最佳答案

发生这种情况是因为您的 associatedtypetypealias 应该是具体的,而不是抽象的。

因此,对于您的情况,StringDataStore 应该是一个,而不是协议(protocol)

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

class StringDataStore: DataStore {
typealias DataType = String

func save(data: String, with key: String) {
//
}

func retreive(from key: String) -> String? {
return nil
}
}

class Test: PersistentDataModel {
typealias DataType = String
typealias DataStoreType = StringDataStore
}

但是,您可以继续使用协议(protocol)并通过在 Test 类中使用额外的泛型条件来解决它:

class Test<T: StringDataStore>: PersistentDataModel where T.DataType == String {
typealias DataStoreType = T
typealias DataType = T.DataType
}

使用它,您可以告诉编译器具体类型将被传递给其他地方的 Test

像这样:

class ConcreteStringDataStore: StringDataStore {
func save(data: String, with key: String) {
//
}

func retreive(from key: String) -> String? {
return nil
}
}

let test = Test<ConcreteStringDataStore>()

关于swift - 如何在 Swift 中处理多个泛型协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54527518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com