# Why can’t key paths refer to instance methods?

**URL:** <https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315>\
**Category:** Discussion\
**Tags:** keypaths, functions\
**Created:** [April 12, 2020, 6:23pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315 "2020-04-12T18:23:27Z")\
**Posts on this page:** 20\
**Page:** 2

<div class="post-metadata">

**Author:** ![Paul\_Cantrell](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/paul_cantrell/32/16764_2.png) [@Paul\_Cantrell](https://forums.swift.org/u/Paul_Cantrell)\
**Post date:** [April 14, 2020, 2:18am UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/21 "2020-04-14T02:18:04Z")

</div>

> [@anandabits](#):
>
> If methods in key paths work like read-only subscripts, all arguments would need to be bound.

I didn’t get that from Joe’s post. @Joe_Groff, is that accurate? It would seem to severely limit the usefulness of this feature, and I don’t see any reason in principle it shouldn’t be allowed.

I would think this, for example, ought to work:

```
func munge(using keyPath: KeyPath<String, (Int) -> Substring>) -> Substring
    "noodles"[keyPath: keyPath](6)
}

munge(using: \.dropFirst) // → "s"
munge(using: \.dropLast) // → "n"
munge(using: \.prefix) // → "noodle"
munge(using: \.suffix) // → "oodles"

```

---

<div class="post-metadata">

**Author:** ![anandabits](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/anandabits/32/355_2.png) [@anandabits](https://forums.swift.org/u/anandabits)\
**Post date:** [April 14, 2020, 2:51am UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/22 "2020-04-14T02:51:04Z")

</div>

Ahh, I can see why you thought that would work now. Maybe I misunderstood what Joe was getting at.

I was bummed that [SE-0042](https://github.com/apple/swift-evolution/blob/master/proposals/0042-flatten-method-types.md) didn't make it in. I wonder if we could make unbound method key path literals compatible with uncurried function types. That would allow `mutating` methods to finally be available in unbound form.

---

<div class="post-metadata">

**Author:** ![Paul\_Cantrell](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/paul_cantrell/32/16764_2.png) [@Paul\_Cantrell](https://forums.swift.org/u/Paul_Cantrell)\
**Post date:** [April 14, 2020, 4:30am UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/23 "2020-04-14T04:30:35Z")

</div>

Unbound mutating methods would indeed be lovely, but they seem a much thornier design space.

Same goes for key paths with argument binding:

```
\Sequence.dropFirst(2) // Should this work?

\Array.index(_:offsetBy:2) // How about one argument bound?

```

Quite a can of worms there — not least the syntax! (I remember some past discussions going around in quite a few circles over the parallel question for unapplied methods.)

* * *

In contrast, the proposal at hand seems quite tractable.

One little hitch is key paths that reference generic methods:

```
struct Foo {
  func bar<T>(_ val: T) -> [T] { … }
}

\Foo.bar // what is the type of this key path?

```

The type of `\Foo.bar` would (I think?) require generalized existentials:

```
some <T> KeyPath<Foo, (T) -> [T]> // made-up syntax

```

…or some other way of introducing new type variables into the types of individual values in Swift.

It seems to me an initial proposal here would have to simply forbid accessing such methods via key path.

* * *

I found myself also worrying about key paths that come from conditional conformances:

```
\Sequence.joined

```

What is the type of this key path? I don't see that it's possible to express it in Swift as the language stands; it would similarly require generalized existentials with embedded where clauses:

```
some <T> KeyPath<T, (T.Element) -> T.Element> // made-up syntax
  where T: Sequence, T.Element: StringProtocol

```

But then I realized that today even _property_ key paths don't work unless the root type can be expressed as a bare type in Swift, e.g.:

```
\Collection.count // protocol 'Collection' can only be used as a generic constraint because it has Self or associated type requirements
\Array.count // error: generic parameter 'Element' could not be inferred
\Array<Int>.count // allowed 

```

…so we can safely rule out such root types for _function_ key paths as well.

---

<div class="post-metadata">

**Author:** ![filip-sakel](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/filip-sakel/32/8697_2.png) [@filip-sakel](https://forums.swift.org/u/filip-sakel)\
**Post date:** [April 14, 2020, 8:25am UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/24 "2020-04-14T08:25:52Z")

</div>

I find the proposal really appealing. If this feature makes it to swift a new map method could be added to the standard library:

```swift
extension Array {
    // Ignore the implementation
    func map<NewValue>(_ keyPath: KeyPath<Element, () -> NewValue>) -> Array<NewValue> {
        map { element in
            element[keyPath: keyPath]()
        }
    }
}

```

that would allow this:

```swift
let array = ["Hello", "World!"]

let transformed = array.map(\.dropFirst) // ["ello", "orld!"]

```

---

<div class="post-metadata">

**Author:** ![Saklad5](https://avatars.discourse-cdn.com/v4/letter/s/4491bb/32.png) [@Saklad5](https://forums.swift.org/u/Saklad5)\
**Post date:** [April 14, 2020, 12:08pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/25 "2020-04-14T12:08:01Z")

</div>

I think blocking off thorny functionality is a decent approach when implementing such things, so long as we don’t design ourselves into a corner. In particular, the syntax should eventually support any functionality that we can think of now, assuming it doesn’t violate basic principles like type safety.

One of my favorite things about Swift is its orthogonality. Finding an exception to it is what prompted this discussion, in the hopes of whittling it down further.

---

<div class="post-metadata">

**Author:** ![anandabits](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/anandabits/32/355_2.png) [@anandabits](https://forums.swift.org/u/anandabits)\
**Post date:** [April 14, 2020, 1:01pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/26 "2020-04-14T13:01:43Z")

</div>

> [@Paul\_Cantrell](#):
>
> Unbound mutating methods would indeed be lovely, but they seem a much thornier design space.

I’m not so sure. If we introduce syntax for unbound method key paths it might be possible to allow them to be used in contexts SE-0042 would have supported:

```swift
func takesMutating(_: (inout Foo) -> Void {}
func takesMutatingWithArg(_: (inout Foo, Int) -> Void) {}

struct Foo {
   mutating func bar() { }
   mutating func baz(_: Int) { }
}

takesMutating(\Foo.bar)
takesMutatingWithArg(\Foo.baz)

// possibly even this:
takesMutating(\.bar)
takesMutatingWithArg(\.baz)

```

What about the above approach seems thorny? IIRC, @Joe_Groff has mentioned method key paths in the context of a path forward for SE-0042 in the past. Perhaps something like this is what he had in mind.

In any case, I think it’s really important that we think about this before pushing forward with a method key path proposal. Even if mutating methods are not supported now, I’d like to know how they fit in as a future direction. It would be a shame to design ourselves into a corner where they are difficult to add later. And it would also be a shame to need an entirely different mechanism in addition to the existing unbound methods and the proposed method key paths.

> [@Paul\_Cantrell](#):
>
> Same goes for key paths with argument binding:
> 
> ```swift
> \Sequence.dropFirst(2) // Should this work?
> 
> \Array.index(_:offsetBy:2) // How about one argument bound?
> 
> ```

The first example there looks very straightforward if you use subscript key paths as a precedent.

The second example with partially supplied arguments is not as straightforward because it requires syntax for the “hole” and is less clear how it might correspond to the key path type. I think this would be interesting to explore but is less important and should probably be left as a future enhancement.

> [@Paul\_Cantrell](#):
>
> The type of `\Foo.bar` would (I think?) require generalized existentials:
> 
> ```swift
> some <T> KeyPath<Foo, (T) -> [T]> // made-up syntax
> 
> ```
> 
> …or some other way of introducing new type variables into the types of individual values in Swift.

I’m a bit out of my league here, but that looks closer to higher-rank types than existentials to me. I’ve never seen higher-rank types discussed outside the context of function types before though so I’m not sure.

---

<div class="post-metadata">

**Author:** ![Paul\_Cantrell](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/paul_cantrell/32/16764_2.png) [@Paul\_Cantrell](https://forums.swift.org/u/Paul_Cantrell)\
**Post date:** [April 14, 2020, 2:35pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/27 "2020-04-14T14:35:10Z")

</div>

> [@Paul\_Cantrell](#):
>
> Unbound mutating methods would indeed be lovely, but they seem a much thornier design space.

I was thinking of unbound methods, not key paths. But…

> [@anandabits](#):
>
> If we introduce syntax for unbound method key paths it might be possible to allow them to be used in contexts SE-0042 would have supported:

…you make an excellent point! At first blush, key paths seem better suited for capturing mutating methods than unbound method references, since they solve the problem of _what_ gets mutated:

```
let a = Foo().mutatingMethod // if we use a, how do we get the mutated Foo?
let b = \Foo.mutatingMethod // if we use b, we have to provide the Foo; problem solved

```

> [@anandabits](#):
>
> I’m a bit out of my league here, but that looks closer to higher-rank types than existentials to me. I’ve never seen higher-rank types discussed outside the context of function types before though so I’m not sure.

Yeah, I realized after I posted that "existential" is the wrong concept here: an existential always has a concrete type at runtime, whereas here `T` remains free until called. (Also, existentials would be “any” and not “some” in my fake syntax examples. 🤨)

Out of my league too, but I think you're right about it being rank-N types. My fake syntax should have been:

```
forall <T> KeyPath<Foo, (T) -> [T]>

```

…or perhaps a more Swift-like term than “forall.” (It’s ironic that Swift, so ML-like in so many ways, doesn’t even have rank 1 function types like 'a → 'a!)

In any case, since `Foo().bar` with no further context wouldn’t be allowed in my [example](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/23), so it follows that `\Foo.bar` shouldn’t be either — and that rules out the problem altogether.

It's worth noting that Swift _does_ currently allow `Foo().bar` in that example if there's enough context to make the type specific:

```
Foo().bar as (Int) -> [Int] // these compile today
Foo().bar as (String) -> [String]

```

…so should these be allowed too?

```
\Foo.bar as KeyPath<Foo, (Int) -> [Int]>
\Foo.bar as KeyPath<Foo, (String) -> [String]>

```

By contract, AFAICT my second example (`\Sequence.joined`) would still be ruled out entirely in the Swift type world of today; there’s no way to sufficiently narrow the types at key path creation time if the root is `Sequence`.

---

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [April 14, 2020, 4:15pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/28 "2020-04-14T16:15:55Z")

</div>

I think there are two features here:

- Allowing key paths to refer to methods, and
- Allowing key path literal syntax to form closures

Allowing the latter doesn't necessarily require that we constrain the feature to methods that fit the model of key paths, so we could still use the syntax to allow for shorthand references to mutating methods, methods with unbound arguments, and things like that which wouldn't really fit the key path model. That was our original intent when adopting the syntax for key paths.

---

<div class="post-metadata">

**Author:** ![filip-sakel](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/filip-sakel/32/8697_2.png) [@filip-sakel](https://forums.swift.org/u/filip-sakel)\
**Post date:** [April 15, 2020, 5:45am UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/29 "2020-04-15T05:45:31Z")

</div>

I think that mutating methods would be better expressed as such:

```
struct Foo {
    mutating func bar() { ... }
}

let keyPath = \Foo.bar // WritableKeyPath<Foo, () -> ()>

let closure: (inout Foo) -> () -> () = \Foo.bar

```

The reason why I propose (inout Foo) -\> () -\> () instead of (inout Foo) -\> () is because if we add parameters to the method ‘bar’ things quickly get complicated. I believe that converting the former closure to the latter is what @anandabits is interested in, but I’m afraid it’s out of the scope of this proposal.

---

<div class="post-metadata">

**Author:** ![anandabits](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/anandabits/32/355_2.png) [@anandabits](https://forums.swift.org/u/anandabits)\
**Post date:** [April 15, 2020, 3:37pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/30 "2020-04-15T15:37:23Z")

</div>

The reason unbound mutating methods are not available today is because method signatures are in curried form. This does not work because it would need to escape the `inout self` and it isn't possible to escape an `inout`.

---

<div class="post-metadata">

**Author:** ![anandabits](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/anandabits/32/355_2.png) [@anandabits](https://forums.swift.org/u/anandabits)\
**Post date:** [April 15, 2020, 3:39pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/31 "2020-04-15T15:39:34Z")

</div>

> [@Joe\_Groff](#):
>
> Allowing the latter doesn't necessarily require that we constrain the feature to methods that fit the model of key paths, so we could still use the syntax to allow for shorthand references to mutating methods, methods with unbound arguments, and things like that which wouldn't really fit the key path model. That was our original intent when adopting the syntax for key paths.

That's what I was wondering. It sounds like a good approach to me. Thanks for clarifying!

---

<div class="post-metadata">

**Author:** ![filip-sakel](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/filip-sakel/32/8697_2.png) [@filip-sakel](https://forums.swift.org/u/filip-sakel)\
**Post date:** [April 16, 2020, 9:15am UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/32 "2020-04-16T09:15:50Z")

</div>

I'm concerned about the way dynamic member lookup will be handled if method key paths are added. Will an instance method be treated as a closure or will we handle instance methods differently?

```swift
struct Foo {
    func bar(a: Int) { ... }
}

@dynamicMemberLookup
struct FooWrapper {
    subscript<Value>(dynamicMember keyPath: KeyPath<Foo, Value>) { ... }
}

let wrapper = FooWrapper()
wrapper.bar(5) // Should instance methods be allowed?
               // If so, are argument labels going to be required
               // or is 'bar' just a closure of type: (Int) -> Void

```

---

<div class="post-metadata">

**Author:** ![DevAndArtist](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/devandartist/32/287_2.png) [@DevAndArtist](https://forums.swift.org/u/DevAndArtist)\
**Post date:** [April 16, 2020, 1:22pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/33 "2020-04-16T13:22:35Z")

</div>

I think parameter labels should be required if you want to pass any parameters.

---

<div class="post-metadata">

**Author:** ![filip-sakel](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/filip-sakel/32/8697_2.png) [@filip-sakel](https://forums.swift.org/u/filip-sakel)\
**Post date:** [April 16, 2020, 1:57pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/34 "2020-04-16T13:57:44Z")

</div>

I agree, but are there any ideas on how to do that?

---

<div class="post-metadata">

**Author:** ![Paul\_Cantrell](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/paul_cantrell/32/16764_2.png) [@Paul\_Cantrell](https://forums.swift.org/u/Paul_Cantrell)\
**Post date:** [April 16, 2020, 3:18pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/35 "2020-04-16T15:18:08Z")

</div>

I'm working on drafting a proposal for this. @Saklad5 and any others, DM me if you’re interested in helping to draft.

---

<div class="post-metadata">

**Author:** ![GeneralD](https://avatars.discourse-cdn.com/v4/letter/g/85e7bf/32.png) [@GeneralD](https://forums.swift.org/u/GeneralD)\
**Post date:** [December 29, 2020, 3:10pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/36 "2020-12-29T15:10:24Z")

</div>

Many people including me would be happy if Swift supported that.

In my case, if the syntax is available, the last line in my code have to work.

```
public extension Collection {
	subscript() -> ArrayMemberLookupReference<Self> {
		.init(source: self)
	}
}

public extension Collection where Element: Collection {
	subscript() -> ArrayMemberLookupReference<[Element.Element]> {
		.init(source: flatten)
	}
}

@dynamicMemberLookup
public struct ArrayMemberLookupReference<C: Collection> {
	fileprivate let source: C
}

extension ArrayMemberLookupReference {
	subscript<Property>(dynamicMember keyPath: KeyPath<C.Element, Property>) -> [Property] {
		source.map { t in t[keyPath: keyPath] }
	}
	
	subscript<Result>(dynamicMember keyPath: KeyPath<C.Element, () -> (Result)>) -> () -> [Result] {
		{ source.map { t in t[keyPath: keyPath] }.map { f in f() } }
	}
	
	subscript<Arg0, Result>(dynamicMember keyPath: KeyPath<C.Element, (Arg0) -> (Result)>) -> (Arg0) -> [Result] {
		{ a0 in source.map { t in t[keyPath: keyPath] }.map { f in f(a0) } }
	}
	
	subscript<Arg0, Arg1, Result>(dynamicMember keyPath: KeyPath<C.Element, (Arg0, Arg1) -> (Result)>) -> (Arg0, Arg1) -> [Result] {
		{ a0, a1 in source.map { t in t[keyPath: keyPath] }.map { f in f(a0, a1) } }
	}
	
	subscript<Arg0, Arg1, Arg2, Result>(dynamicMember keyPath: KeyPath<C.Element, (Arg0, Arg1, Arg2) -> (Result)>) -> (Arg0, Arg1, Arg2) -> [Result] {
		{ a0, a1, a2 in source.map { t in t[keyPath: keyPath] }.map { f in f(a0, a1, a2) } }
	}
}

fileprivate extension Collection where Element: Collection {
	var flatten: [Element.Element] {
		flatMap { $0 }
	}
}

struct Person {
	let name: String
	let age: Int
	let friends: [Person]
}

extension Person {
	func greeting(message: String) -> String {
		"\(message) \(name)"
	}
}

let people: [Person] = [.init(name: "me", age: 32, friends: [.init(name: "Tom", age: 40, friends: [])]), .init(name: "you", age: 28, friends: [.init(name: "Nancy", age: 10, friends: []), .init(name: "Freddie", age: 20, friends: [])])]
let totalAge = people[].age.reduce(0, +) // 60
let ourFriends = people[].friends[].name.reduce("", +) // "TomNancyFreddie"

let greetings = people[].greeting("Hi!") // ["Hi! me", "Hi! you"]

```

---

<div class="post-metadata">

**Author:** ![Anachron](https://avatars.discourse-cdn.com/v4/letter/a/bc8723/32.png) [@Anachron](https://forums.swift.org/u/Anachron)\
**Post date:** [January 1, 2021, 2:43am UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/37 "2021-01-01T02:43:20Z")

</div>

Regarding the key-paths to static methods discussed on Apr 20th: That would be awesome! If you are a library writer and you have some often-used protocol with tricky to remember conforming types, you may be inclined to create an empty enum ("namespace") where you put a lot of static constants or static methods to create stuff:

```swift
protocol Disposable{
func dispose()
}

enum Disposables {
static func create(_ dispose: @escaping () -> Void) -> some Disposable{...}
}

```

In order to nudge people to actually use this enum, you may want to replace methods using a `Disposable` with methods taking a static method or static constant. Currently this is only possible with instance properties or instance methods. One can make that work, but I tend to feel dirty afterwards.

---

<div class="post-metadata">

**Author:** ![bermudalocket](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bermudalocket/32/12517_2.png) [@bermudalocket](https://forums.swift.org/u/bermudalocket)\
**Post date:** [February 11, 2021, 7:18pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/38 "2021-02-11T19:18:25Z")

</div>

Any update on your progress, Paul?

I would definitely like to see this. It's one of the very, very, very (very... very... very...) few things I miss from Java.

A relatively common place I run into this is with the Combine framework:

```
var cancellables = [AnyCancellable]()

func someTask() {
    ...
    cancellables.forEach { $0.cancel() }
    ...
}

```

The `forEach` line could be more succinct:

```
cancellables.forEach(\.cancel)

```

---

<div class="post-metadata">

**Author:** ![Paul\_Cantrell](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/paul_cantrell/32/16764_2.png) [@Paul\_Cantrell](https://forums.swift.org/u/Paul_Cantrell)\
**Post date:** [February 11, 2021, 11:29pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/39 "2021-02-11T23:29:08Z")

</div>

The proposal is here:

> [@Allow key paths to reference unapplied instance methods](https://forums.swift.org/t/allow-key-paths-to-reference-unapplied-instance-methods/35582):
>
> [Allow key paths to reference unapplied instance methods](https://github.com/pcantrell/swift-evolution/blob/method-keypaths/proposals/NNNN-method-keypaths.md) The [original key path proposal](https://github.com/apple/swift-evolution/blob/master/proposals/0161-key-paths.md) expressly limited key paths to be able to reference only properties and subscripts: \Person.name // KeyPath\<Person, String\> \Person.pets[0] // KeyPath\<Person, Pet\> This proposal adds the ability for key paths to reference instance methods, optionally specifying argument names: \Person.sing // KeyPath\<Person, () -\> Sound\> \Person.sing(melody:lyrics:) // KeyPat…

It seemed well received on first blush, with a few interesting questions in the comments, but neither I nor anybody else has created an implementation so it can move forward in the process. I poked at implementing it for an evening myself, but 2020 took over and I haven’t touched it since. Would love to get back to it at some point.

---

<div class="post-metadata">

**Author:** ![bermudalocket](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/bermudalocket/32/12517_2.png) [@bermudalocket](https://forums.swift.org/u/bermudalocket)\
**Post date:** [February 14, 2021, 6:25pm UTC](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/40 "2021-02-14T18:25:16Z")

</div>

Thanks for the response!

Is this a feasible project for a newbie? I'm very interested in contributing to Swift but I have no experience at the compiler level. I do have experience with C(++) and I hold a Master's degree in mathematics, so I'm hoping that's enough of a foundation to get my foot in the door.

Slightly off-topic, I saw your comment in the pitch thread re: remote teaching and I can empathize! Hope you've found your groove.

[Previous page](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315.md?page=1)

[Next page](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315.md?page=3)
