Control de Flujo
## Objetivos de Aprendizaje
- Dominar declaraciones if-else
- Trabajar con declaraciones switch
- Usar bucles (for, while, repeat-while)
- Comprender declaraciones guard
- Aprender declaraciones de transferencia de control
## Declaraciones If
### If Basico
```swift
let puntuacion = 85
if puntuacion >= 60 {
print("Aprobado!")
}
```
### If-Else
```swift
let edad = 20
if edad >= 18 {
print("Adulto")
} else {
print("Menor")
}
```
### If-Else If
```swift
let calificacion = 85
if calificacion >= 90 {
print("A")
} else if calificacion >= 80 {
print("B")
} else if calificacion >= 70 {
print("C")
} else if calificacion >= 60 {
print("D")
} else {
print("F")
}
```
### If Anidado
```swift
let x = 10
if x > 0 {
if x < 100 {
print("x esta entre 0 y 100")
}
}
```
## Declaraciones Switch
### Switch Basico
```swift
let dia = 3
switch dia {
case 1:
print("Lunes")
case 2:
print("Martes")
case 3:
print("Miercoles")
case 4:
print("Jueves")
case 5:
print("Viernes")
case 6, 7:
print("Fin de semana")
default:
print("Dia invalido")
}
```
### Multiples Valores
```swift
let caracter = "a"
switch caracter {
case "a", "e", "i", "o", "u":
print("Vocal")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
print("Consonante")
default:
print("No es una letra")
}
```
### Coincidencia de Rangos
```swift
let puntuacion = 85
switch puntuacion {
case 90...100:
print("A")
case 80..<90:
print("B")
case 70..<80:
print("C")
case 60..<70:
print("D")
default:
print("F")
}
```
### Enlace de Valores
```swift
let punto = (2, -3)
switch punto {
case (let x, 0):
print("En el eje x en \(x)")
case (0, let y):
print("En el eje y en \(y)")
case let (x, y):
print("Punto en (\(x), \(y))")
}
```
### Clausula Where
```swift
let punto2 = (3, 3)
switch punto2 {
case let (x, y) where x == y:
print("En la diagonal (x = y)")
case let (x, y) where x == -y:
print("En la anti-diagonal")
case let (x, y):
print("Punto en (\(x), \(y))")
}
```
### Switch con Tuplas
```swift
let persona = (nombre: "Alicia", edad: 30)
switch persona {
case ("Alicia", 30):
print("Coincidencia perfecta!")
case (_, 30):
print("El nombre no coincide")
case ("Alicia", _):
print("La edad no coincide")
default:
print("Sin coincidencia")
}
```
## Bucles For
### For-In con Rango
```swift
for i in 1...5 {
print(i) // 1, 2, 3, 4, 5
}
```
### For-In con Arreglo
```swift
let frutas = ["manzana", "banana", "cereza"]
for fruta in frutas {
print(fruta)
}
```
### For-In con Diccionario
```swift
let edades = ["Alicia": 30, "Roberto": 25, "Carlos": 35]
for (nombre, edad) in edades {
print("\(nombre) tiene \(edad) anos")
}
```
### For-In con Indice
```swift
let colores = ["rojo", "verde", "azul"]
for (indice, color) in colores.enumerated() {
print("\(indice): \(color)")
}
```
### Ignorar Valores
```swift
let valores = [1, 2, 3, 4, 5]
let conteo = valores.count
for _ in 0.. 0 {
print(cuentaRegresiva)
cuentaRegresiva -= 1
}
print("Despegue!")
```
### Repeat-While (Do-While)
```swift
var numero = 1
repeat {
print(numero)
numero += 1
} while numero <= 5
// Se ejecuta al menos una vez, aunque la condicion sea falsa
var vacio = false
repeat {
print("Se ejecuta una vez")
} while vacio
```
## Transferencia de Control
### Break
Sale del bucle anticipadamente:
```swift
let numeros = [1, 2, 3, 4, 5]
for num in numeros {
if num == 3 {
break
}
print(num) // 1, 2
}
```
### Continue
Salta la iteracion:
```swift
for num in 1...5 {
if num == 3 {
continue
}
print(num) // 1, 2, 4, 5
}
```
### Fallthrough
Continua al siguiente caso (a diferencia del tipico switch):
```swift
let num = 2
switch num {
case 1:
print("Uno")
fallthrough
case 2:
print("Dos")
fallthrough
case 3:
print("Tres")
default:
print("Otro")
}
// Salida: Dos, Tres
```
## Declaraciones Guard
### Conceptos Basicos de Guard
```swift
func saludar(nombre: String?) {
guard let nombre = nombre else {
print("No se proporciono nombre")
return
}
print("Hola, \(nombre)!")
}
saludar(nombre: "Alicia") // Hola, Alicia!
saludar(nombre: nil) // No se proporciono nombre
```
### Guard con Multiples Condiciones
```swift
func procesar(edad: Int?, nombre: String?) {
guard let edad = edad, let nombre = nombre else {
print("Faltan datos requeridos")
return
}
guard edad >= 18 else {
print("\(nombre) es muy joven")
return
}
print("\(nombre) tiene \(edad) y puede continuar")
}
```
### Guard en Bucles
```swift
let datos: [Int?] = [1, 2, nil, 4, 5]
for elemento in datos {
guard let valor = elemento else {
continue
}
print(valor * 2) // 2, 4, 8, 10
}
```
## Retorno Anticipado con Guard
```swift
func configurar(etiqueta: UILabel?) {
guard let etiqueta = etiqueta else { return }
etiqueta.text = "Hola"
etiqueta.textColor = .black
etiqueta.font = UIFont.systemFont(ofSize: 17)
}
```
## Declaraciones Etiquetadas
### Bucles Etiquetados
```swift
bucleExterno: for i in 1...3 {
bucleInterno: for j in 1...3 {
if i == 2 && j == 2 {
break bucleExterno // Sale del bucle externo
}
print("i=\(i), j=\(j)")
}
}
```
### Switch Etiquetado
```swift
let matriz = [[1, 2], [3, 4]]
var encontrado = false
buscar: for (i, fila) in matriz.enumerated() {
for (j, valor) in fila.enumerated() {
if valor == 3 {
encontrado = true
print("Encontrado en (\(i), \(j))")
break buscar
}
}
}
```
## Resumen
- `if`, `if-else`, `if-else if-else` para condiciones
- `switch` con casos, rangos, enlace de valores, clausulas where
- Bucles `for-in` con rangos, arreglos, diccionarios
- Bucles `while` y `repeat-while`
- `break` sale de bucles/switches; `continue` salta iteraciones
- `guard` para salida anticipada con enlace opcional
- `fallthrough` continua al siguiente caso
- Declaraciones etiquetadas para control de flujo anidado
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →