In Swift, what does the unapplied reference LengthRule.check produce, and how does it differ from the bound reference rule.check?
answer
- instance first, then arguments
- curried function type
- bound reference closes over self
- struct copied, class retained
- mutating methods refuse
basics
~20 sLengthRule.check is a curried (LengthRule) -> (String) -> Bool: pass an instance, get the method. rule.check is a (String) -> Bool bound to its receiver, holding a copy of a struct or a strong reference to a class instance.
solid answer
~40 sReferencing an instance method through its type, `LengthRule.check`, gives an unapplied method reference of type `(LengthRule) -> (String) -> Bool`: call it with an instance to get the method bound to that instance, then call that. Referencing it through an instance, `rule.check`, gives a `(String) -> Bool` with the receiver already captured. For a struct the receiver is copied at that moment, so later changes to `rule` are not seen; for a class the reference holds the object strongly, keeping it alive as long as the function value lives. Through a base class, an unapplied reference still dispatches to a subclass's override. Swift rejects referencing a `mutating` method as a function value in either form, with "cannot reference 'mutating' method as function value".
code
swift · 21 linesstruct LengthRule {
var minimum: Int
func check(_ input: String) -> Bool { input.count >= minimum }
}
let unapplied = LengthRule.check // (LengthRule) -> (String) -> Bool
var rule = LengthRule(minimum: 3)
let bound = rule.check // (String) -> Bool, holds a copy of rule
rule.minimum = 10
print(unapplied(rule)("abcd")) // false: uses the current rule
print(bound("abcd")) // true: the copy still says 3
final class SignupForm {
func validate(_ input: String) -> Bool { !input.isEmpty }
deinit { print("form released") }
}
var form: SignupForm? = SignupForm()
var handler: ((String) -> Bool)? = form!.validate // strong reference to the form
form = nil // nothing printed yet
handler = nil // prints "form released"go deeper
Recognise that methods can be referenced without calling them, through the type or through an instance, and that the two have different types.
Write out the curried type of an unapplied reference and show how to call it, and explain that a bound reference already has its receiver.
Predict what a bound reference captures: a copy for a struct, a strong reference for a class with the cycle risk that follows, dynamic dispatch through a base class, and why mutating methods are rejected.
Decide when method references make callback-heavy code clearer and when a closure is safer, given lifetime and copying effects reviewers can easily miss.
## Two ways to name a method as a value An instance method in Swift can be turned into a function value without calling it, in two forms: - **Unapplied**, through the type: `LengthRule.check`. - **Bound**, through an instance: `rule.check`. Given ```swift struct LengthRule { var minimum: Int func check(_ input: String) -> Bool { input.count >= minimum } } ``` the two references have different types and different behaviour. | Reference | Type | Receiver | |---|---|---| | `LengthRule.check` | `(LengthRule) -> (String) -> Bool` | Supplied later, on each call | | `rule.check` | `(String) -> Bool` | Captured when the reference is made | | `LengthRule.check(rule)` | `(String) -> Bool` | The instance passed in | ## The unapplied reference is curried An unapplied method reference takes the instance first and returns the method bound to it, so a full call is `LengthRule.check(rule)("abcd")`. Function types group from right to left, which is why `(LengthRule) -> (String) -> Bool` reads as a function returning a function. A proposal to flatten this into `(LengthRule, String) -> Bool` (Swift Evolution SE-0042) was accepted but never implemented and is now marked rejected because it would break source, so the curried form is the language's rule. Useful consequences: - You can store **which operation** to run separately from **which instance** to run it on, for example a table of form actions applied to whichever form is active. - Through a **class**, the reference respects overriding: `FormScreen.validate` called with a `StrictScreen` instance runs `StrictScreen`'s override, because calling it is an ordinary dynamic method call. ## The bound reference captures its receiver A bound reference behaves like a closure that captured `self`: 1. **Struct receiver**: the value is **copied** when `rule.check` is evaluated. Setting `rule.minimum = 10` afterwards does not affect the stored function, which still checks against the old minimum. 2. **Class receiver**: the function holds a **strong reference** to the instance. The object cannot be deallocated while the function value is alive, so storing `form.validate` in a property of the same `form` creates a reference cycle. The mechanics of cycles and their fixes belong to the memory material. 3. **Later reads**: for a class, the bound method sees later changes to the object's properties, because it holds the object, not a copy. ## Tracing the code example The example's printed lines follow directly from these rules: 1. `unapplied(rule)("abcd")` binds the **current** `rule`, whose minimum is now 10, so it prints `false`. 2. `bound("abcd")` uses the copy taken when `rule.minimum` was still 3, so it prints `true`. 3. Setting `form = nil` prints nothing: `handler` still holds the `SignupForm`. 4. Setting `handler = nil` drops the last strong reference, so `deinit` runs and prints `form released`. ## What cannot be referenced - **Mutating methods.** `counter.increment` and `Counter.increment`, where `increment` is `mutating`, both fail with "cannot reference 'mutating' method as function value". A mutating method needs write access to one specific variable for the duration of the call, and a function value detached from that variable has none to offer. Wrap the call in a closure over the variable instead. - **Stored properties.** `LengthRule.minimum` is not a function; the compiler reports that the instance member cannot be used on the type. Turning a property into a function is the job of key paths, covered in their own material. ## When to use which - Use a **bound reference** to hand a specific object's behaviour to a callback slot, the same way you would pass a closure, and remember it keeps a class instance alive. - Use an **unapplied reference** when the instance varies per call, or when you want to pass "the `check` operation of any `LengthRule`" to something that will supply instances. - Prefer a closure when you need to break a cycle with a capture list or call a mutating method.
- Through a base class, does FormScreen.validate called with a StrictScreen run the override?Yes. The unapplied reference names the method without choosing an implementation; applying it to an instance makes an ordinary dynamic call, so a `StrictScreen` passed in runs `StrictScreen`'s override.
- How do you pass a mutating struct method as a callback?You cannot reference it directly; Swift reports "cannot reference 'mutating' method as function value". Write a closure that performs the call on a variable it can mutate, such as `{ counter.increment() }` where `counter` is a captured `var`, or move the state into a class so the method no longer needs to be `mutating`.
- Why might storing button.handleTap in the button's own property leak?A bound method on a class instance holds that instance strongly. If the instance also holds the function value, each keeps the other alive and neither is freed. A closure with a weak capture of the instance breaks the cycle; the details of weak and unowned captures live with closures and memory management.
- LengthRule.check has the flattened type (LengthRule, String) -> Bool.
- A bound struct method sees later changes made to the original variable.
- A bound method on a class instance holds the object weakly.
- Any method, including a mutating one, can be stored as a function value.
- An unapplied reference through a base class always runs the base implementation.