gpt4 book ai didi

swift - 如何为类类型提供默认的下标协议(protocol)一致性?

转载 作者:行者123 更新时间:2023-11-28 07:19:50 26 4
gpt4 key购买 nike

用“class”标记 CacheManager 解决了我的问题。

案例:一个简单的缓存器,mutating get 不是我想要的,那么对于引用类型或类类型应该怎么做?

protocol Cacher {
associatedtype K
associatedtype V
subscript (key: K) -> V? {get set}
}

protocol MemoryCacher: Cacher {}

protocol FileCacher: Cacher {}

已更新。添加 PrimayCacher | SecondaryCacher 关联类型

protocol CacheManager {
associatedtype Key
associatedtype Value
associatedtype PrimaryCacher: MemoryCacher where PrimaryCacher.K == Key, PrimaryCacher.V == Value
associatedtype SecondaryCacher: FileCacher where SecondaryCacher.K == Key, SecondaryCacher.V == Value
var primaryCacher: PrimaryCacher { get set }
var secondaryCacher: SecondaryCacher{ get set }
subscript(key: Key) -> Value? { get set }
}

//try to provide a default subscript conformance, but actually not for the `mutating` get
extension CacheManager {
subscript(key: Key) -> Value? {
mutating get {
guard let result = primaryCacher[key] else {
if let value = secondaryCacher?[key] {
primaryCacher[key] = value // the mutating is required for this
return value
}
return nil
}
return result
}
set {
primaryCacher[key] = newValue
secondaryCacher?[key] = newValue
}
}
}

最佳答案

你只需要给 AnyObject 添加一个类型限制,所有的类都符合。

extension CacherManager where Self: AnyObject {
subscript(key: Key) -> Value? {
get {
guard let result = primaryCacher[key] else {
if let value = secondaryCacher?[key] {
primaryCacher[key] = value // the mutating is required for this
return value
}
return nil
}
return result
}
set {
primaryCacher[key] = newValue
secondaryCacher?[key] = newValue
}
}
}

我还必须稍微修改您的 CacheManager 声明,以便编译代码并将所需的协议(protocol)方法添加到您的 MemoryCacherFileCacher从问题中省略。

protocol Cacher {
associatedtype K
associatedtype V
subscript (key: K) -> V? {get set}
}

class MemoryCacher<K, V>: Cacher {
private var value: V?

subscript(key: K) -> V? {
get {
return value
}
set {
value = newValue
}
}
}

class FileCacher<K, V>: Cacher {
private var value: V?

subscript(key: K) -> V? {
get {
return value
}
set {
value = newValue
}
}
}

protocol CacheManager {
associatedtype Key
associatedtype Value
var primaryCacher: MemoryCacher<Key,Value> { get set }
var secondaryCacher: FileCacher<Key,Value>? { get set }
subscript(key: Key) -> Value? { get set }
}

关于swift - 如何为类类型提供默认的下标协议(protocol)一致性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58519085/

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