Mapping between different KeyPath types

Let's say that I created a function that accepts a key path of type KeyPath<Element, Value> as its parameter. Now I would like to convert it to a key path of type KeyPath<(offset: Int, element: Element), Value> that is required by another function that I'm going to call. Is it possible to achieve something like this?

Example code:

func my<Element, Value>(keyPath: KeyPath<Element, Value>) {
    other(keyPath: /* Something here to get proper keyPath */)
}

func other<Element, Value>(keyPath: KeyPath<(offset: Int, element: Element), Value> ) {}
  1. Construct a key path that goes from (offset: Int, element: Element) to Element. Let's call it base.
  2. Now you can append your key path to base to go from the tuple type to Value.

Like this:

func my<Element, Value>(keyPath: KeyPath<Element, Value>) {
    let base = \(offset: Int, element: Element).element
    other(keyPath: base.appending(path: keyPath))
}

func other<Element, Value>(keyPath: KeyPath<(offset: Int, element: Element), Value> ) {}
3 Likes

Thanks, that's simpler than I expected.

2 Likes