SwiftSeniorOpen-ended
Can a computed property be `async` or `throw` errors?
Explanation & Code
Answer:
Yes — since Swift 5.5, a read-only computed property can mark its getter async, throws, or both, and callers must use await / try to read it.
Code Example:
struct RemoteImage {
let url: URL
var data: Data {
get async throws {
let (data, _) = try await URLSession.shared.data(from: url)
return data
}
}
}
let image = RemoteImage(url: someURL)
let bytes = try await image.data
Key Points:
- Only read-only computed properties (and subscripts) can be effectful — a property with a setter cannot.
- Use this for values that are naturally properties but need async work, such as an actor-isolated or lazily loaded value.
- If the operation takes parameters or does heavy work, a method is still clearer.
Rate your understanding: