004*:函数
正文
一:函数
print("一:函数") /* 一:函数 1:函数的声明:关键字 函数声明 形参 返回值 2:函数返回值是元组 3:外部参数 */ // 1:函数的声明:关键字 函数声明 形参 返回值 func runoob(name: String, site: String) -> String { return name + site } print(runoob(name: "Google:", site: "www.google.com")) // 2:函数返回值是元组 func minMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty { return nil } var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { // for value in array { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) } if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) { print("最小值为 \(bounds.min),最大值为 \(bounds.max)") } // 3:外部参数 func pow(firstArg a: Int, secondArg b: Int) -> Int { var res = a for _ in 1..<b { res = res * a } return res } let b = pow(firstArg:5, secondArg:3) print(b) // 4:函数作为参数 func sum(a: Int, b: Int) -> Int { return a + b } var addition: (Int, Int) -> Int = sum print("输出结果: \(addition(40, 89))") func another(addition: (Int, Int) -> Int, a: Int, b: Int) { print("输出结果: \(addition(a, b))") } another(addition: sum, a: 10, b: 20) // 5: 函数嵌套:函数作为返回值,外部的函数可以调用函数内定义的函数。 func calcDecrement(forDecrement total: Int) -> () -> Int { var overallDecrement = 0 func decrementer() -> Int { overallDecrement -= total return overallDecrement } return decrementer } let decrem = calcDecrement(forDecrement: 30) print(decrem()) print("一:函数")