定义函数
- 定义:func 函数名(参数1: 类型, 参数2: 类型, ...) -> 返回结果的类型 {执行语句}
- 调用:var 变量名称 = 函数名(变量1, 变量2, ...)
//乘法函数
func multiply(x: Int, y: Int) -> Int {
return x * y
}
var z = multiply(x: 3, y: 4) //z = 12
let h = multiply(x: -1, y: -100) //h = 100
- 无返回值时可省略返回语句 func 函数名(参数1: 类型, 参数2: 类型, ...) {}
func welcome1() {
print("welcome to")
print("learn swift4!")
}
welcome1()
func maxMin() -> (Int, Double) {
return (Int.max, 0.0)
}
let zzz = maxMin()
print(zzz.1)
func add2(x: Int, increment: Int = 2) -> Int {
return x + increment
}
let ccc = add2(x: 3)
let ddd = add2(x: 4, increment: 6)
func add3(_ x: Int, _ y: Int) -> Int {
return x + y
}
add3(2, 3)
func add(number: Int ...) -> Int {
var sum = 0
for i in number {
sum += i
}
return sum
}
add(number: 1, 2, 3)
函数类型
- 函数类型:包含参数和返回类型的简写形式,可以像普通变量那样使用,一般用于函数式编程. (Int,Int) -> Int
func calculate(x: Int, y: Int, method: (Int, Int) -> Int) -> Int {
return method(x,y)
}
func add(x: Int, y: Int) -> Int {
return x + y
}
func mutiply(x: Int, y: Int) -> Int {
return x * y
}
let z = calculate(x: 2, y: 3, method: add)
let i = calculate(x: 2, y: 3, method: mutiply)
print("z = \(z), i = \(i)")