To unwrap an optional and pass it to a function I normally use:
var optionalInt: Int?
optionalInt.map { someFunctionThatTakes(aNonOptional: $0) }
Now I have an optional error that I would like to throw if it is not nil:
var optionalError: Error?
optionalError.map { throw $0 }
This won't work because the closure passed to map can't throw.
An alternative solution would be to youse the full if let syntax:
if let theError = optionalError { throw theError }
But this uses the variable name theError twice and is more error prone than the beautiful .map implementation.
Does anyone know a cleaner way to implement this?
This won't work because the closure passed to map can't throw.
That's not true. The closure passed to
func map<U>(_ transform: (Wrapped) throws -> U) rethrows -> U?
can throw an error. But that makes the map() call itself a (re-)throwing expression, therefore it must be called with try:
var optionalError: Error?
// ...
try optionalError.map { throw $0 }
I would probably still use
if let theError = optionalError { throw theError }
which is very clear, and does not use Optional.map for its side effects (discarding the return value of type Void?).
if you don't use try in front of map method it will give error
Call can throw but is not marked with 'try'
Instead, use try to actually throw an error.
enum IntParsingError: Error {
case overflow
case invalidInput(String)
}
var optionalError: Error? = IntParsingError.overflow
do {
try optionalError.map { throw $0 }
} catch {
print(error)
}
You can also use flatMap because of it evaluates the closure optional instance is not nil
optionalError.flatMap(throw $0)
But Still, If let would be the best way to handle optional error instead of map and flatMap.
You can create extension for Swift.Error
extension Swift.Error {
func throwIfNeeded() throws {
throw self
}
}
And call it on optional error
try error?.throwIfNeeded()