if let y guard let en Swift
Desenvolver por sombra: mismo nombre, no-opcional adentro.
func report(entry: String?) {
// guard let unwraps for the rest of the function, or bails.
guard let entry else {
print("No entry logged")
return
}
print("Logbook: \(entry)")
}
let winds: [String: String] = ["morning": "SW 12"]
// if let unwraps for one block; the shadowed name is non-optional.
if let noon = winds["noon"] {
print("Noon wind \(noon)")
} else if let morning = winds["morning"] {
print("Falling back to morning: \(morning)")
}
report(entry: "rounded the pin early")
report(entry: nil)
Cómo funciona
guard let entry elsedesenvuelve para toda la función o sale.if let noon = winds["noon"]desenvuelve para un bloque.- La escalera else-if prueba los respaldos en orden.
Palabras clave y builtins usados aquí
Stringelsefuncguardifletprintreturn
El intento, en números
- Líneas
- 20
- Caracteres a escribir
- 503
- Tokens
- 111
- Ritmo de tres estrellas
- 65 tpm
Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 102 segundos.
Paso 2 de 3 en Opcionales; paso 11 de 27 en Fundamentos del lenguaje.