Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

431
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda