Throwing properties in Swift

Tram Ho

Swift 5.5 allows us to throw error even when defining computed properties, not just in function anymore.

How to define throwing properties in Swift

To define throwing properties, we just need to use the keyword throws as follows:

Since initialization of Data can throw error, by defining our computed properties in throw form, we can catch this error .

Without this new feature, we would have to define it as method:

Using custom-defined errors

We can throw custom-defined errors. Eg:

In the above example we define 1 custom error is imageNotFound. If the url we passed in does not exist in the cache, we will throw this error.

Throwing setter for computed properties

Unfortunately we won’t be able to define throwing setter cho computed properties right now. If we do that, we will see the following error:

This limitation exists to  simplify the implementation of throwing properties.

Should I use throwing property or throwing method?

Nor is there a fixed rule for deciding whether to choose computed properties or method.

We should keep in mind that using computed properties or method  is all about increasing the readability of our code. As such, we should decide based on what each of these refers to.

Usually method is better in case need to compute a lot, because method usually implies “need to compute”, and can produce  side effect, while computed properties usually applies to case where only  format data is needed. simple.

Source: https://www.avanderlee.com/swift/throwing-properties/

Share the news now