Keypaths on arrays

Hello friends,

I have problem in accessing values from an array through KeyPath.
scenario looks like: entity-> [Bank]->owner?->name

element: ReferenceWritableKeyPath<B, V>
in array: ReferenceWritableKeyPath<A, [B]>

How would you guys write the get method which will return value in the form of <A, [V]>

2 Likes

There’s nothing built-in that would do it, but you can always roll your own:

extension Collection {
    subscript<Value>(map keyPath: KeyPath<Element, Value>) -> [Value] {
        get { map { $0[keyPath: keyPath] } }
    }
    
    subscript<Value>(map keyPath: ReferenceWritableKeyPath<Element, Value>) -> [Value] {
        get { self[map: keyPath as KeyPath<Element, Value>] }
        nonmutating set {
            for (i, value) in zip(indices, newValue) {
                self[i][keyPath: keyPath] = value
            }
        }
    }
}

extension MutableCollection {
    subscript<Value>(map keyPath: WritableKeyPath<Element, Value>) -> [Value] {
        get { self[map: keyPath as KeyPath<Element, Value>] }
        set {
            for (i, value) in zip(indices, newValue) {
                self[i][keyPath: keyPath] = value
            }
        }
    }
}
8 Likes

how can i use it in my code?