How do I declare that a computed property 'throws' in Swift?
Solution 1:
This functionality is added for read-only computed properties in Swift 5.5 as part of SE-0310 (included in Xcode 13).
Based on SE-0310, the syntax would be:
class SomeClass {
var someProperty: Int {
get throws {
throw Err("SNAFU")
}
}
}
Here is the previous answer for versions of Swift prior to 5.5:
You cannot throw from a computed property. You must use a function if you want to throw. The Declarations section of the Language Reference part at the end of The Swift Programming Language only lists throws
(and rethrows
) as a keyword for function and initializer declarations.
Solution 2:
While it's not possible (yet) to throw
from computed properties in Swift, I found Chris Lattner himself adresses this very same question on one of Apple Developer Forums threads:
We agree that you should be able to mark the getters and setters as "throws" in subscripts and computed properties, but haven't gotten there yet. We are likely to support this at some time, but it isn't clear if it will make it in time for Swift 2.
Solution 3:
Let me suggest a workaround: a property can be declared as having type of Result<DesiredPropertyType, Error>
. This way it can be accessed like this:
do {
try self.failableProperty.get()
} catch {
...
}
get()
is a built-in method of Swift's Result
.
UPDATE: this is getting addressed in Swift 5.5 with "effectful read-only properties": https://github.com/apple/swift-evolution/blob/main/proposals/0310-effectful-readonly-properties.md.