← Swift EspañolChapter 05 of 13

Funciones

## Objetivos de Aprendizaje - Crear funciones con parametros - Retornar valores de funciones - Usar parametros inout - Dominar closures y funciones de orden superior - Comprender tipos de funciones ## Funciones Basicas ### Declaracion de Funcion ```swift func decirHola() { print("Hola!") } decirHola() // Llama la funcion ``` ### Con Tipo de Retorno ```swift func saludar() -> String { return "Hola, Mundo!" } let mensaje = saludar() print(mensaje) ``` ## Parametros ### Parametro Unico ```swift func cuadrado(numero: Int) -> Int { return numero * numero } let resultado = cuadrado(numero: 5) // 25 ``` ### Multiples Parametros ```swift func sumar(a: Int, b: Int) -> Int { return a + b } let suma = sumar(a: 3, b: 4) // 7 ``` ### Etiquetas de Parametros ```swift func saludar(nombre: String) { print("Hola, \(nombre)!") } saludar(nombre: "Alicia") ``` ### Nombres Externos y Locales ```swift func saludar(a nombre: String) { print("Hola, \(nombre)!") } saludar(a: "Alicia") // Externo: a, Local: nombre ``` ### Omitir Nombres Externos ```swift func sumar(_ a: Int, _ b: Int) -> Int { return a + b } sumar(3, 4) // No se necesitan nombres externos ``` ### Parametros por Defecto ```swift func saludar(_ nombre: String, saludo: String = "Hola") { print("\(saludo), \(nombre)!") } saludar("Alicia") // Hola, Alicia! saludar("Roberto", saludo: "Hi") // Hi, Roberto! ``` ### Parametros Variadicos ```swift func sumar(numeros: Int...) -> Int { var total = 0 for numero in numeros { total += numero } return total } sumar(numeros: 1, 2, 3, 4, 5) // 15 sumar(numeros: 10, 20) // 30 ``` ## Valores de Retorno ### Retorno Unico ```swift func multiplicar(a: Int, b: Int) -> Int { return a * b } ``` ### Multiples Retornos (Tuplas) ```swift func dividir(_ a: Int, entre b: Int) -> (cociente: Int, residuo: Int) { return (a / b, a % b) } let resultado = dividir(10, entre: 3) print(resultado.cociente) // 3 print(resultado.residuo) // 1 ``` ### Retorno Opcional ```swift func encontrarPrimero(impar: [Int]) -> Int? { for num in impar { if num % 2 == 1 { return num } } return nil } let primero = encontrarPrimero(impar: [2, 4, 6, 8, 9]) if let impar = primero { print("Encontrado impar: \(impar)") } ``` ## Parametros Inout Modificar valores originales: ```swift func intercambiar(_ a: inout Int, _ b: inout Int) { let temp = a a = b b = temp } var x = 10 var y = 20 intercambiar(&x, &y) print("x: \(x), y: \(y)") // x: 20, y: 10 ``` ### Inout con Arreglos ```swift func duplicarValores(_ arreglo: inout [Int]) { for i in 0.. Int func sumar(_ a: Int, _ b: Int) -> Int { return a + b } // () -> Void func decirHola() { print("Hola!") } ``` ### Asignar a Variable ```swift func multiplicar(_ a: Int, _ b: Int) -> Int { return a * b } let operacion: (Int, Int) -> Int = multiplicar let resultado = operacion(3, 4) // 12 ``` ### Pasar como Argumento ```swift func aplicarOperacion(_ fn: (Int, Int) -> Int, a: Int, b: Int) -> Int { return fn(a, b) } let resultado = aplicarOperacion(multiplicar, a: 3, b: 4) // 12 ``` ### Retornar de Funcion ```swift func obtenerOperacion(_ tipo: String) -> (Int, Int) -> Int { switch tipo { case "sumar": return { $0 + $1 } case "multiplicar": return { $0 * $1 } default: return { $0 - $1 } } } let op = obtenerOperacion("sumar") op(5, 3) // 8 ``` ## Closures ### Expresion de Closure Basica ```swift let saludo = { (nombre: String) in print("Hola, \(nombre)!") } saludo("Alicia") ``` ### Sintaxis Abreviada ```swift let numeros = [1, 2, 3, 4, 5] // Closure completo let duplicados = numeros.map({ (n: Int) -> Int in return n * 2 }) // Con inferencia de tipo let duplicados2 = numeros.map({ n in n * 2 }) // Trailing closure let duplicados3 = numeros.map { n in n * 2 } // Argumentos abreviados let duplicados4 = numeros.map { $0 * 2 } ``` ### Capturar Valores ```swift func hacerContador() -> () -> Int { var conteo = 0 return { conteo += 1 return conteo } } let contador = hacerContador() contador() // 1 contador() // 2 contador() // 3 ``` ## Funciones de Orden Superior ### Map Transformar elementos: ```swift let numeros = [1, 2, 3, 4, 5] let alCuadrado = numeros.map { $0 * $0 } // [1, 4, 9, 16, 25] let cadenas = numeros.map { String($0) } // ["1", "2", "3", "4", "5"] ``` ### Filter Seleccionar elementos: ```swift let numeros = [1, 2, 3, 4, 5, 6] let pares = numeros.filter { $0 % 2 == 0 } // [2, 4, 6] let mayoresA3 = numeros.filter { $0 > 3 } // [4, 5, 6] ``` ### Reduce Combinar elementos: ```swift let numeros = [1, 2, 3, 4, 5] let suma = numeros.reduce(0) { $0 + $1 } // 15 let producto = numeros.reduce(1) { $0 * $1 } // 120 // Abreviado let suma2 = numeros.reduce(0, +) // 15 ``` ### FlatMap Aplanar arreglos: ```swift let anidado = [[1, 2], [3, 4], [5, 6]] let plano = anidado.flatMap { $0 } // [1, 2, 3, 4, 5, 6] ``` ### CompactMap Eliminar nils: ```swift let opcionales: [Int?] = [1, nil, 3, nil, 5] let noNulos = opcionales.compactMap { $0 } // [1, 3, 5] ``` ### Encadenamiento ```swift let numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let resultado = numeros .filter { $0 % 2 == 0 } // [2, 4, 6, 8, 10] .map { $0 * $0 } // [4, 16, 36, 64, 100] .reduce(0, +) // 220 ``` ## Recursividad ### Funcion Recursiva ```swift func factorial(_ n: Int) -> Int { if n <= 1 { return 1 } return n * factorial(n - 1) } factorial(5) // 120 ``` ### Fibonacci ```swift func fibonacci(_ n: Int) -> Int { if n <= 1 { return n } return fibonacci(n - 1) + fibonacci(n - 2) } fibonacci(10) // 55 ``` ## Funciones Anidadas ```swift func funcionExterna() { var x = 10 func funcionInterna() { x += 5 print("Interno: \(x)") } funcionInterna() print("Externo: \(x)") } funcionExterna() // Interno: 15 // Externo: 15 ``` ## Resumen - Funciones declaradas con palabra clave `func` - Parametros tienen nombres externos y locales - Parametros por defecto, variadicos, e `inout` disponibles - Retornar valores unicos o tuplas (incluyendo opcionales) - Tipos de funciones: `(tiposParam) -> tipoRetorno` - Closures: funciones anonimas con palabra clave `in` - Orden superior: map, filter, reduce, flatMap, compactMap - Capturar valores del alcance circundante - Soportan recursividad y funciones anidadas

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →