class SomeClass { var someProperty: Int { throw Err("SNAFU") } }
For code like the above, the swift binary complains 'error is not handled because the enclosing function is not declared 'throws'.
How do I declare that 'someProperty' 'throws' in the above?
class SomeClass { var someProperty throws: Int { } }
and
class SomeClass { var someProperty: throws Int { } }
and
class SomeClass { var someProperty: Int throws { } }
don't seem to work.
Throwing properties in Swift can only be defined for computed properties. This limitation exists to make the implementation as simple as possible for now.
In Swift, we use the static keyword to create a static property. For example, class University { // static property static var name: String = "" ... } Here, name is the static property.
Computed Properties. In addition to stored properties, classes, structures, and enumerations can define computed properties, which don't actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.
Computed properties are part of a family of property types in Swift. Stored properties are the most common which save and return a stored value whereas computed ones are a bit different. A computed property, it's all in the name, computes its property upon request.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With