Reputation: 12983
The following pattern is quite common in certain places in my code, but it doesn't feel Swifty:
if let res = calcSomething() {
return res
} else {
throw err.invalidSomething
}
In English: return the calue of calcSomething()
if it returned a non-nil, throw an exception otherwise.
I was hoping for a structure that looks like the following:
return calcSomething() ?? throw err.invalidSomething
But so far didn't find anything similar. Am I missing something?
Upvotes: 3
Views: 3773
Reputation: 31645
For such a case, I would prefer to use the guard
statement instead, so it would be similar to:
func myFunction() throws {
guard let res = calcSomething() else {
throw err.invalidSomething
}
// keep going now...
// if something went wrong, you might want to throw another error:
throw err.invalidSomething
// if everything is ok:
return res
}
The guard
would bounce the calling of the function, by throwing the desired error directly if calcSomething()
is nil
.
About return calcSomething() ?? throw err.invalidSomething
:
It seems to be an obvious goal when implementing such a function, however as some point it is not so logical to the language because the nil-coalescing operator (??
):
The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is
nil
. The expression a is always of an optional type. The expression b must match the type that is stored inside a.The nil-coalescing operator is shorthand for the code below:
a != nil ? a! : b
which means that it returns
a value as a result; throw err.invalidSomething
does not a value to be returned, instead it is an exceptional case for something went wrong that throws an error.
Upvotes: 1
Reputation: 3802
I don't think you can use null coalesce
in a return statement. However, you can do something like this
guard let res = calcSomething() else { throw err.invalidSomething }
return res
Upvotes: 2