In a Swift networking helper, when should a retry policy be a stored property of function type rather than a protocol with one method?
answer
- one behaviour, many shapes
- a struct wrapping a function
- static factories at the call site
- function types conform to nothing
basics
~20 sUse a stored function property when the policy is one behaviour with ad hoc variants and test stubs. Use a protocol when it needs several requirements, visible state, or conformances such as Equatable or Codable, which function types cannot have.
solid answer
~50 sA struct like `RetryPolicy { var shouldRetry: (Int, Int) -> Bool }` accepts any function, closure or bound method of that type, needs no new type per variant, and with static factories reads well at the call site: `fetchStatus(path, retry: .upTo(3))`. A test can pass a one-line stub. The price is that function types conform to no protocol, so a struct holding one loses synthesized `Equatable`, `Hashable` and `Codable`, cannot be compared or logged meaningfully, and hides its state inside captures. A protocol such as `RetryStrategy` with conforming types keeps state in named properties, groups related requirements such as `shouldRetry` and `delay`, can adopt those conformances, and supports generic use via `some RetryStrategy`. Choose the function property for a single swappable behaviour; choose the protocol once the policy has several requirements or must be inspected or stored.
code
swift · 20 linesstruct RetryPolicy {
var shouldRetry: (_ attempt: Int, _ statusCode: Int) -> Bool
static var never: RetryPolicy { RetryPolicy { _, _ in false } }
static func upTo(_ maxAttempts: Int) -> RetryPolicy {
RetryPolicy { attempt, status in attempt < maxAttempts && status >= 500 }
}
}
func fetchStatus(_ path: String, retry: RetryPolicy = .upTo(3)) -> Int {
var attempt = 1
var status = 503 // stand-in for a real request
while retry.shouldRetry(attempt, status) {
attempt += 1
status = attempt == 3 ? 200 : 503
}
return status
}
print(fetchStatus("/profile"), fetchStatus("/profile", retry: .never)) // 200 503go deeper
Know that a struct can hold a function in a property and call it like a method, and that a protocol is the other way to make behaviour swappable.
Explain what each shape costs: lost Equatable and Codable synthesis and hidden state for the function property, a new type per variant for the protocol, and how callAsFunction fits between them.
Pick the shape from the requirements in front of you: how many related decisions, whether state must be inspected or persisted, and who will add new variants. Refactor between them when a policy outgrows one function.
Set a codebase convention for extension points so teams do not mix closure-bag structs and protocols arbitrarily, and revisit it when policies must be configured remotely or logged.
## Two ways to make behaviour swappable A networking helper that retries failed requests needs to ask "should I try again?" without hard-coding the answer. Swift offers two common shapes for that question. **A stored property of function type**, usually inside a small struct: ```swift struct RetryPolicy { var shouldRetry: (_ attempt: Int, _ statusCode: Int) -> Bool } ``` **A protocol with one method**, implemented by named types: ```swift protocol RetryStrategy { func shouldRetry(attempt: Int, statusCode: Int) -> Bool } struct CappedRetry: RetryStrategy { var maxAttempts: Int func shouldRetry(attempt: Int, statusCode: Int) -> Bool { attempt < maxAttempts && statusCode >= 500 } } ``` Both compile to "call a function chosen elsewhere". They differ in what else the policy can be. ## What the function property gives you - **Any function value fits.** A global function, a closure expression, a nested function returned by a factory, or a bound method such as `config.shouldRetry` all have the type `(Int, Int) -> Bool`. - **No type per variant.** `static func upTo(_ maxAttempts: Int) -> RetryPolicy` and a computed `static var never` produce policies on demand, and the call site reads like an enum: `fetchStatus(path, retry: .never)`. - **Trivial test stubs.** A test writes `RetryPolicy { _, _ in false }` inline instead of declaring a mock type. - **Ordinary call syntax.** `retry.shouldRetry(attempt, status)`, with no labels, because labels are not part of a function type. ## Swapping it in a test The function property shines in tests, because a stub is a value rather than a type: ```swift let retryOnce = RetryPolicy { attempt, _ in attempt < 2 } let status = fetchStatus("/profile", retry: retryOnce) ``` With a protocol, the same stub needs a conforming type declared somewhere, even if it is two lines long. For a single decision, that difference adds up across a test suite. ## What it costs 1. **No protocol conformances.** Function types cannot conform to protocols, so a struct with a function-typed stored property loses synthesized `Equatable`, `Hashable` and `Codable`. Declaring `Equatable` produces "type 'RetryPolicy' does not conform to protocol 'Equatable'", with a note that the stored property's function type is "preventing synthesized conformance". 2. **Hidden state.** Whatever the function captured is invisible: you cannot print it, assert on it in a test, or persist it. 3. **One property per behaviour.** Related decisions, such as whether to retry and how long to wait, become separate properties with no compiler check that they agree. 4. **Escaping by construction.** The memberwise initializer's parameter for a function-typed property is escaping, so forwarding a non-escaping function parameter into it fails with "passing non-escaping parameter 'rule' to function expecting an '@escaping' closure". The rules for `@escaping` live with closures and capture lists. ## What the protocol gives you, and costs | Concern | Function-typed property | Protocol with one method | |---|---|---| | New variant | A value: a closure or a factory | A new conforming type | | State | Hidden in captures | Named stored properties | | Several related requirements | Separate properties | One protocol, checked together | | `Equatable`, `Codable` | Not available for the function | Available to conforming types | | Generic constraint | Not applicable | `some RetryStrategy` or a generic parameter | | Test double | One-line closure | A small mock type | The protocol's cost is ceremony: a declared type for each policy. Its gain is that the policy becomes a thing with a name, visible state and conformances. ## Making a named type callable If you like call syntax but need a named type, Swift 5.2's `callAsFunction` (Swift Evolution SE-0253) lets an instance be called directly: with `func callAsFunction(_ attempt: Int, _ statusCode: Int) -> Bool`, `policy(2, 503)` works. The instance does **not** convert to a function type, though: passing `policy` to a `(Int, Int) -> Bool` parameter fails with "cannot convert value of type 'RetryPolicy' to expected argument type '(Int, Int) -> Bool'"; pass the bound method `policy.callAsFunction` instead. ## A rule of thumb - One decision, many small variants, mostly configured in code: **function property**. - Several cooperating decisions, state that must be visible, compared or persisted, or variants other modules add as types: **protocol**. - Under Swift 6 language mode, a stored function that crosses isolation domains also needs `@Sendable`; that rule belongs to the concurrency material.
- Why is never written as a computed static var rather than static let in the example?A computed property builds a fresh value on each access and stores nothing, so it is not shared mutable global state. In Swift 6 language mode a `static let` of a type that is not `Sendable`, such as a struct holding a plain function, is flagged as not concurrency-safe; the computed form sidesteps that. Making the stored function `@Sendable` is the other route.
- How do you get a RetryPolicy into an API that expects a (Int, Int) -> Bool?Pass the stored function itself, `policy.shouldRetry`, which already has that type. If the type instead defines `callAsFunction(_:_:)`, pass `policy.callAsFunction`; the instance alone does not convert to a function type, even though `policy(2, 503)` call syntax works.
- A struct holding a closure property still gets a synthesized Equatable.
- A protocol is always required to make a behaviour testable.
- A type with callAsFunction can be passed wherever a matching function type is expected.
- Stored function properties are called with their parameter names as labels.
- A function property can expose its captured state for logging or tests.