一、函数的基本使用
//1、无参无返回值的函数
func about(){
print("iphone7")
}
about()
func about1() -> Void {
print("iphone7")
}
about1()
//2、无参有返回值的函数
func readMessage() -> String{
return "吃饭了吗"
}
print(readMessage())
//3、有参无返回值的函数
func callPhone(phoneNum: String){
print("打电话\(phoneNum)")
}
callPhone(phoneNum: "15669993907")
//4、有参数有返回值的函数
func sum(num1: Int, num2: Int) -> Int{
return num1 + num2
}
print(sum(num1: 3, num2: 2))
//5、多参数多返回值的函数
func minMax(num1: Int, num2: Int, num3: Int) -> (min: Int, max: Int) {
var max: Int
var min: Int
max = ( (num1 > num2 ? num1 : num2) > num3) ? (num1 > num2 ? num1 : num2) : num3;
min = ( (num1 > num2 ? num2 : num1) > num3) ? num3 : (num1 > num2 ? num2 : num1);
return (min, max)
}
print(minMax(num1: 10, num2: 8, num3: 16))
二、函数的使用注意 --- 参数名
//省略参数标签
func buySomeThing(_ vegetables: String, money: Int) -> String {
return "我买了\(vegetables),花了\(money)元"
}
print(buySomeThing("苹果", money: 120))
//默认形式参数值
func buy(parameter: Int = 12) {
print("花了\(parameter)")
}
buy(parameter: 6)
buy()
//可变形式参数
func sumNumber(_ numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
print(sumNumber(1, 2, 3, 4, 5))
//输入输出形式参数 值传递转换为指针传递
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
三、函数的使用注意 --- 函数类型
//这个函数的类型都是 (Int, Int) -> Int
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
//使用函数类型 --- 它的类型是‘一个能接受两个 Int值的函数,并返回一个 Int值
var mathFunction: (Int, Int) -> Int = addTwoInts
print("Result: \(mathFunction(2, 3))")
//函数类型作为形式参数
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
//函数类型作为返回类型 --- 写法是在函数的返回箭头( ->)后立即写一个完整的函数类型。
//这两个函数的类型都是 (Int) -> Int
func stepForward(_ input: Int) -> Int {
return input + 1
}
func stepBackward(_ input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backwards: currentValue > 0)
print(moveNearerToZero)
while currentValue != 0 {
print("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
四、函数嵌套
func chooseFunction(backwards: Bool) -> (Int) -> Int {
func forward(input: Int) -> Int { return input + 1 }
func backward(input: Int) -> Int { return input - 1 }
return backwards ? backward : forward
}
var currenValue = -4
let nearerToZero = chooseStepFunction(backwards: currentValue > 0)
while currenValue != 0 {
print("\(currentValue)... ")
currentValue = nearerToZero(currentValue)
}