Errores en Swift
Lanzamientos tipados ruteados por do, try y catch.
enum EntryError: Error {
case missingSailNumber
case lateEntry(daysLate: Int)
}
func register(boat: String, sail: Int?) throws -> String {
guard let sail else { throw EntryError.missingSailNumber }
return "\(boat) registered as #\(sail)"
}
// do/try/catch routes thrown errors to their handlers.
do {
print(try register(boat: "Kestrel", sail: 207))
print(try register(boat: "Mystery", sail: nil))
} catch EntryError.missingSailNumber {
print("Rejected: no sail number on the form")
} catch {
print("Rejected: \(error)")
}
Cómo funciona
enum EntryError: Errordeclara los casos de fallo.throwsmarca la función;trymarca cada llamada riesgosa.- Los catch específicos van antes del
errorcomodín.
Palabras clave y builtins usados aquí
IntStringcasecatchdoelseenumfuncguardletprintreturnthrowthrowstry
El intento, en números
- Líneas
- 19
- Caracteres a escribir
- 523
- Tokens
- 113
- Ritmo de tres estrellas
- 65 tpm
Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 104 segundos.
Paso 1 de 3 en Errores y alcance; paso 22 de 27 en Fundamentos del lenguaje.