Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

434
Vistas
What is the cleanest way in swift to throw an optional error?

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?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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?).

over 4 years ago · Santiago Trujillo Denunciar

0

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.

over 4 years ago · Santiago Trujillo Denunciar

0

You can create extension for Swift.Error

extension Swift.Error {
   func throwIfNeeded() throws {
       throw self
   }
}

And call it on optional error

try error?.throwIfNeeded()
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda