0

有没有办法在其访问器中推断属性的 KeyPath?

我有以下设置:

protocol LazyCacheProvider {
    associatedtype Value
    associatedtype Key where Key: Hashable
    typealias ValueBuilder = () -> Value

    func get(_ key: Key, constructor: @escaping ValueBuilder) -> Value
    func set(_ value: Value, forKey: Key)

}

class LazyCache<V, P>: LazyCacheProvider {
    typealias Parent = P
    typealias Value = V
    typealias Key = KeyPath<P, V>
    typealias ValueBuilder = () -> Value

    private var cache: [Key: Value] = [:]

    func get(_ key: Key, constructor: @escaping ValueBuilder ) -> Value {
        if let value = cache[key] {
            return value
        }
        let value = constructor()
        set(value, forKey: key)
        return value
    }

    func set(_ value: Value, forKey key: Key) {
        cache[key] = value
    }
}

class YourOtherClass: MyClass {
    private let intCache = LazyCache<Int, YourOtherClass>()
    private let stringCache = LazyCache<String, YourOtherClass>()

    override var words: String { stringCache.get(\.words) {
        super.words + " Hello"
    } }

    override var value: Int { intCache.get(\.value) {
        super.value * 15
    } }

}

我正在使用KeyPath而不是String这样我就不会出现拼写错误。

如何\.value从 的访问器中推断出YourOtherClass.value

4

0 回答 0