How about using Result
in a computed property? (* Suggestion, not recommendation)
throw
even in Computed property!You can't write code like this in Swift (as of Swift 5):
enum E: Error {
case someError
}
struct S {
var someProperty: throws Int { //⛔️ Can't compile
if Bool.random() {
return 0
} else {
throw E.someError
}
}
}
That's because you can't use the keyword throws
for properties in the first place. throws
can only be used with func
(or closures), so if you want to do the same, you usually do this:
enum E: Error {
case someError
}
struct S {
func someProperty() throws -> Int {
if Bool.random() {
return 0
} else {
throw E.someError
}
}
}
… By the way, isn't there a way to use Result
? ??
enum E: Error {
case someError
}
struct S {
var someProperty: Result<Int, Error> {
return .init(catching: {
if Bool.random() {
return 0
} else {
throw E.someError
}
})
}
}
Result
?There is no particular merit, but ... If you dare to mention:
-* Realize the feeling that "I want the property to be a property. I don't want to use func
. "*.
--Evaluation can be delayed until you call .get ()
.
It's just an idea, but I personally think that it may be convenient (sometimes) to use it with a property * that is not * public
(∴ completed within that module).
Recommended Posts