Optional binding en Swift: if let, guard let, while let y el nuevo if let taquigráfico

Cuando la variable desenvuelta tiene el mismo nombre que el optional, puedes omitir el lado derecho:

var nombre: String? = "Ana"

// Antes de Swift 5.7:
if let nombre = nombre { print(nombre) }

// Swift 5.7+:
if let nombre { print(nombre) }  // equivalente
guard let nombre else { return }
print(nombre)

while let

var stack: [Int] = [1, 2, 3, 4, 5]
while let top = stack.popLast() {
    print(top)  // 5, 4, 3, 2, 1
}

// Leer lineas de stdin hasta EOF
while let linea = readLine() {
    print("Leido: (linea)")
}

Por qué evitar el forced unwrap

El forced unwrap ! es un EXC_BAD_INSTRUCTION esperando ocurrir. Úsalo solo cuando tengas la certeza absoluta de que el valor existe y no puedas usarlo de otro modo. Cada ! en producción es una deuda técnica. En tests, las aserciones con XCTUnwrap son preferibles porque dan mensajes de error claros.

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP