typestar

Result en Swift

Éxito o fallo como un valor, con switch como cualquier enum.

// Result stores success or failure as a value you can pass around.
enum ProtestError: Error {
    case filedLate
}

func hearProtest(minutesAfter: Int) -> Result<String, ProtestError> {
    guard minutesAfter <= 90 else {
        return .failure(.filedLate)
    }
    return .success("Protest heard, redress granted")
}
// A Result switches like any enum.
for delay in [30, 120] {
    switch hearProtest(minutesAfter: delay) {
    case .success(let outcome):
        print(outcome)
    case .failure(let error):
        print("Dismissed: \(error)")
    }
}

Cómo funciona

  1. Result<String, ProtestError> nombra ambos desenlaces en el tipo.
  2. .success y .failure construyen; guard elige entre ellos.
  3. Un switch desempaca la carga del caso que haya llegado.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
20
Caracteres a escribir
501
Tokens
98
Ritmo de tres estrellas
65 tpm

Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 90 segundos.

Escribe este fragmento

Paso 2 de 3 en Errores y alcance; paso 23 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →

Result en otros lenguajes