Skip to content

Commit a1daab7

Browse files
authored
Merge pull request #2675 from amritpan/method-keypaths
[SE-NNNN] Method and Initializer Key Paths
2 parents 2567513 + be98eb8 commit a1daab7

File tree

1 file changed

+172
-0
lines changed

1 file changed

+172
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
# Method and Initializer Key Paths
2+
3+
* Proposal: [SE-0479](0479-method-and-initializer-keypaths.md)
4+
* Authors: [Amritpan Kaur](https://github.com/amritpan), [Pavel Yaskevich](https://github.com/xedin)
5+
* Review Manager: [Becca Royal-Gordon](https://github.com/beccadax)
6+
* Status: **Active Review (April 22 ... May 5, 2025)**
7+
* Implementation: [swiftlang/swift#78823](https://github.com/swiftlang/swift/pull/78823), [swiftlang/swiftsyntax#2950](https://github.com/swiftlang/swift-syntax/pull/2950), [swiftlang/swiftfoundation#1179](https://github.com/swiftlang/swift-foundation/pull/1179)
8+
* Experimental Feature Flag: `KeyPathWithMethodMembers`
9+
* Review: ([pitch](https://forums.swift.org/t/pitch-method-key-paths/76678))
10+
11+
## Introduction
12+
13+
Swift key paths can be written to properties and subscripts. This proposal extends key path usage to include references to method members, such as instance and type methods, and initializers.
14+
15+
## Motivation
16+
17+
Key paths to method members and their advantages have been explored in several discussions on the Swift forum, specifically to [unapplied instance methods](https://forums.swift.org/t/allow-key-paths-to-reference-unapplied-instance-methods/35582) and to [partially and applied methods](https://forums.swift.org/t/pitch-allow-keypaths-to-represent-functions/67630). Extending key paths to include reference to methods and initializers and handling them similarly to properties and subscripts will unify instance and type member access for a more consistent API. Key path methods and initializers will also enjoy all of the benefits offered by existing key path component kinds, e.g. simplify code by abstracting away details of how these properties/subscripts/methods are modified/accessed/invoked, reusability via generic functions that accept key paths to methods as parameters, and supporting dynamic invocation while maintaining type safety.
18+
19+
## Proposed solution
20+
21+
We propose the following usage:
22+
23+
```swift
24+
struct Calculator {
25+
func square(of number: Int) -> Int {
26+
return number * number * multiplier
27+
}
28+
29+
func cube(of number: Int) -> Int {
30+
return number * number * number * multiplier
31+
}
32+
33+
init(multiplier: Int) {
34+
self.multiplier = multiplier
35+
}
36+
37+
let multiplier: Int
38+
}
39+
40+
// Key paths to Calculator methods
41+
let squareKeyPath = \Calculator.square
42+
let cubeKeyPath = \Calculator.cube
43+
```
44+
45+
These key paths can then be invoked dynamically with a generic function:
46+
47+
```swift
48+
func invoke<T, U>(object: T, keyPath: KeyPath<T, (U) -> U>, param: U) -> U {
49+
return object[keyPath: keyPath](param)
50+
}
51+
52+
let calc = Calculator(multiplier: 2)
53+
54+
let squareResult = invoke(object: calc, keyPath: squareKeyPath, param: 3)
55+
let cubeResult = invoke(object: calc, keyPath: cubeKeyPath, param: 3)
56+
```
57+
58+
Or used to dynamically create a new instance of Calculator:
59+
60+
```swift
61+
let initializerKeyPath = \Calculator.Type.init(multiplier: 5)
62+
```
63+
64+
This proposed feature homogenizes the treatment of member declarations by extending the expressive power of key paths to method and initializer members.
65+
66+
## Detailed design
67+
68+
Key path expressions can refer to instance methods, type methods and initializers, and imitate the syntax of non-key path member references.
69+
70+
### Argument Application
71+
72+
Key paths can reference methods in two forms:
73+
74+
1. Without argument application: The key path represents the unapplied method signature.
75+
2. With argument application: The key path references the method with arguments already applied.
76+
77+
Continuing our `Calculator` example, we can write either:
78+
79+
```swift
80+
let squareWithoutArgs: KeyPath<Calculator, (Int) -> Int> = \Calculator.square
81+
let squareWithArgs: KeyPath<Calculator, Int> = \Calculator.square(of: 3)
82+
```
83+
84+
If the member is a metatype (e.g., a static method, class method, initializer, or when referring to the type of an instance), you must explicitly include `.Type` in the key path root type.
85+
86+
```swift
87+
struct Calculator {
88+
static func add(_ a: Int, _ b: Int) -> Int {
89+
return a + b
90+
}
91+
}
92+
93+
let addKeyPath: KeyPath<Calculator.Type, Int> = \Calculator.Type.add(4, 5)
94+
```
95+
96+
Here, `addKeyPath` is a key path that references the add method of `Calculator` as a metatype member. The key path’s root type is `Calculator.Type`, and the value resolves to an applied instance method result type of`Int`.
97+
98+
### Overloads
99+
100+
Keypaths to methods with the same base name and distinct argument labels can be disambiguated with explicit argument labels:
101+
102+
```swift
103+
struct Calculator {
104+
var subtract: (Int, Int) -> Int { return { $0 + $1 } }
105+
func subtract(this: Int) -> Int { this + this}
106+
func subtract(that: Int) -> Int { that + that }
107+
}
108+
109+
let kp1 = \Calculator.subtract // KeyPath<Calculator, (Int, Int) -> Int
110+
let kp2 = \Calculator.subtract(this:) // KeyPath<Calculator, (Int) -> Int>
111+
let kp3 = \Calculator.subtract(that:) // KeyPath<Calculator, (Int) -> Int>
112+
let kp4 = \Calculator.subtract(that: 1) // KeyPath<Calculator, Int>
113+
```
114+
115+
### Implicit closure conversion
116+
117+
This feature also supports implicit closure conversion of key path methods, allowing them to used in expressions where closures are expected, such as in higher order functions:
118+
119+
```swift
120+
struct Calculator {
121+
func power(of base: Int, exponent: Int) -> Int {
122+
return Int(pow(Double(base), Double(exponent)))
123+
}
124+
}
125+
126+
let calculators = [Calculator(), Calculator()]
127+
let results = calculators.map(\.power(of: 2, exponent: 3))
128+
```
129+
130+
### Dynamic member lookups
131+
132+
`@dynamicMemberLookup` can resolve method references through key paths, allowing methods to be accessed dynamically without explicit function calls:
133+
134+
```swift
135+
@dynamicMemberLookup
136+
struct DynamicKeyPathWrapper<Root> {
137+
var root: Root
138+
139+
subscript<Member>(dynamicMember keyPath: KeyPath<Root, Member>) -> Member {
140+
root[keyPath: keyPath]
141+
}
142+
}
143+
144+
let dynamicCalculator = DynamicKeyPathWrapper(root: Calculator())
145+
let subtract = dynamicCalculator.subtract
146+
print(subtract(10))
147+
```
148+
149+
### Effectful value types
150+
151+
Methods annotated with `nonisolated` and `consuming` are supported by this feature. However, noncopying root and value types [are not supported](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0437-noncopyable-stdlib-primitives.md#additional-future-work). `mutating`, `throws` and `async` are not supported for any other component type and will similarly not be supported for methods. Additionally keypaths cannot capture closure arguments that are not `Hashable`/`Equatable`.
152+
153+
### Component chaining
154+
155+
Component chaining between methods or from method to other key path types is also supported with this feature and will continue to behave as `Hashable`/`Equatable` types.
156+
157+
```swift
158+
let kp5 = \Calculator.subtract(this: 1).signum()
159+
let kp6 = \Calculator.subtract(this: 2).description
160+
```
161+
162+
## Source compatibility
163+
164+
This feature has no effect on source compatibility.
165+
166+
## ABI compatibility
167+
168+
This feature does not affect ABI compatibility.
169+
170+
## Implications on adoption
171+
172+
This feature has no implications on adoption.

0 commit comments

Comments
 (0)