Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare that a computed property 'throws' in Swift?

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.

like image 810
math4tots Avatar asked Oct 02 '15 01:10

math4tots


People also ask

Can a computed property throw Swift?

Throwing properties in Swift can only be defined for computed properties. This limitation exists to make the implementation as simple as possible for now.

How do I declare a property in Swift?

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.

How is computed property defined?

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.

What is a computed or calculated property in a class in Swift?

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.


2 Answers

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.

like image 135
Charles A. Avatar answered Oct 07 '22 11:10

Charles A.


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.

like image 26
paperlib Avatar answered Oct 07 '22 10:10

paperlib