skip to content

In Swift, how do you declare a computed property whose getter is async or throws, and what can such a property not have?

level: seniorimportance: nice to knowfreq 20%

answer

  1. effects after get
  2. async before throws
  3. try await at the call site
  4. read-only, and no key paths

basics

~20 s

Write the effects after get, as in var celsius: Double { get async throws { ... } }, and read it with try await. Such a property (Swift 5.5) must be read-only: no setter, no observers, no key path.

solid answer

~50 s

**Effectful read-only properties** (SE-0310, Swift 5.5) let a computed property's getter be `async`, `throws`, or both: `var celsius: Double { get async throws { ... } }`, with `async` before `throws` ("'async' must precede 'throws'"). Callers write `try await thermometer.celsius`; omitting either marker is a compile error. Since Swift 6.0 a getter may also use typed throws, `get throws(SensorError)`. The property must be **read-only**: a setter is rejected with "'set' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'", observers likewise, and forming a key path to it fails with "cannot form key path to property with 'throws' or 'async'". The same syntax works on subscripts. A conforming or overriding property may have the same or fewer effects than the one it satisfies. Use one when the value reads like data but may wait or fail.

code

swift · 25 lines
swift
enum SensorError: Error { case offline }

struct RemoteThermometer {
    var isOnline: Bool

    var celsius: Double {
        get async throws {
            guard isOnline else { throw SensorError.offline }
            try await Task.sleep(nanoseconds: 1_000_000)   // simulated network read
            return 21.5
        }
    }
}

func report(_ thermometer: RemoteThermometer) async {
    do {
        let reading = try await thermometer.celsius
        print("reading:", reading)
    } catch {
        print("failed:", error)
    }
}

await report(RemoteThermometer(isOnline: true))    // reading: 21.5
await report(RemoteThermometer(isOnline: false))   // failed: offline

go deeper

for a junior

Recall that a computed property's getter can be marked async or throws, and that callers then write try and await when reading it.

for a middle

Explain the syntax, effects after get with async before throws, and the read-only rule that bans setters and observers.

for a senior

Decide between effectful properties and methods, remember key paths cannot reach them, and treat adding effects to a public property as a source-breaking change.

for a principal

Set API guidance for a module: when a fetch or failing read may be exposed as a property, and when a verb-named method better signals cost and side effects.

## Declaring an effectful getter Before Swift 5.5, a computed property could not suspend or throw: a value that had to be fetched or might fail had to be a method, `func celsius() async throws -> Double`. **SE-0310, effectful read-only properties**, implemented in Swift 5.5, lets the getter itself carry effects. The effects are written **after** the `get` keyword, mirroring where a function writes them after its parameter list: ```swift var celsius: Double { get async throws { guard isOnline else { throw SensorError.offline } return try await fetchReading() } } ``` Rules on the declaration: - the three legal forms are `get async`, `get throws` and `get async throws`; writing `get throws async` fails with "'async' must precede 'throws'"; - since Swift 6.0, typed throws works here too: `get throws(SensorError)` lets callers catch a concrete error type; - the property must be a computed `var` with a `get` accessor and nothing else. Read-only subscripts accept the same syntax, `subscript(day: Int) -> Reading { get async throws { ... } }`. ## Using one A read of an effectful property is marked exactly like a call to an effectful function: 1. An `async` getter must be read with `await`, from an asynchronous context; otherwise the compiler reports "expression is 'async' but is not marked with 'await'". 2. A `throws` getter must be read with `try` (or `try?` / `try!`); otherwise "property access can throw but is not marked with 'try'". 3. With both, the usual form is `try await thermometer.celsius`, inside a `do`/`catch` or a throwing function. Because the markers appear at every read, an effectful property cannot hide its cost the way an ordinary computed property can. ## What an effectful property cannot have | Feature | Allowed? | What the compiler says | |---|---|---| | A `set` accessor | No | "'set' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'" | | `willSet` / `didSet` | No | "'didSet' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'" | | A key path, `\RemoteThermometer.celsius` | No | "cannot form key path to property with 'throws' or 'async'" | | `lazy` or stored storage | No | an effectful property is always computed | | `static` or `class` | Yes | type properties may be effectful too | The proposal explains the read-only limit as a scope decision: defining how async or throwing setters interact with `inout`, observers, property wrappers and writable subscripts was too large for one proposal, so it was deferred. Key paths are excluded because a `KeyPath` value carries no effects in its type. ## Substitution: same or fewer effects When an effectful property takes part in substitution, the rule matches functions: - a property that satisfies a protocol requirement declared `{ get async throws }` may have the **same or fewer** effects, so a plain synchronous property satisfies it, while a throwing getter cannot satisfy a plain `{ get }` requirement; - an overriding property in a subclass may likewise have the same or fewer effects than the property it overrides. The full rules for protocol requirements and for overriding are covered with protocol requirements and with subclassing; this lesson needs only the direction of the rule. ## Property or method? Choose an effectful property when the value **reads like data**: no parameters, no side effects a caller would care about, and a name that is a noun, such as `celsius`, `thumbnail` or `contents`. Choose a method when the operation takes arguments, changes state, or is costly enough that a verb name helps, such as `reload()`. Some guidance applies either way: - an `async` getter is re-run on every read; if the result should be reused, store it after the first `await`; - a throwing getter should throw for genuine failures, not to signal an ordinary absent value, which an optional return type expresses better; - adding `async` or `throws` to an existing public property is a source-breaking change, because every caller must add `await` or `try`. How `await` suspends and what runs while a task is suspended is the subject of the material on asynchronous functions; the property syntax is the part that belongs to properties.

  • Why does Swift not allow a setter on an async or throwing property?
    SE-0310 limited effects to read-only properties on purpose: how async or throwing setters should interact with inout, modify accessors, observers, property wrappers and writable subscripts was left for later work. The compiler enforces it: "'set' accessor is not allowed on property with 'get' accessor that is 'async' or 'throws'". Expose a method such as setTarget(_:) async throws instead.
  • Can a protocol requirement declared { get async throws } be satisfied by an ordinary synchronous property?
    Yes. A witness may have the same or fewer effects than the requirement, so a plain var celsius: Double { 20 } conforms. The reverse fails: a throwing getter cannot satisfy a plain { get } requirement, because callers of the requirement would not write try.

  • An async getter can also have an async setter.
  • Callers read an async property without await; Swift awaits it automatically.
  • You can pass a key path to an async property to map or sort.
  • A throwing getter can only use untyped throws.
  • Effects are written before var, like a modifier on the declaration.