函數(shù)的定義與調(diào)用
func greet(person: String) -> String {
let greeting = "Hello, " + person + "!"
return greeting
}
簡化版
func greetAgain(person: String) -> String {
return "Hello again, " + person + "!"
}
print(greetAgain(person: "Anna"))
// 打印“Hello again, Anna!”
無參無返回值
func test1()->Void{
print("這是一個(gè)無參無返回值的函數(shù)")
}
test1()
func test2()->(){
print("這是一個(gè)無參無返回值的函數(shù)")
}
test2()
func test3(){//最常用
print("這是一個(gè)無參無返回值的函數(shù)")
}
test3()
有參無返回值
func call(phoneNumber:String){
print("給\(phoneNumber)打電話")
}
call(phoneNumber:"10001")
無參有返回值
func getMsg()->String{
return "這是一條來自10086的信息"
}
print(getMsg())
函數(shù)類型
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
return a * b
}
addTwoInts 和 multiplyTwoInts。
注:這兩個(gè)函數(shù)都接受兩個(gè) Int 值, 返回一個(gè) Int 值。
這兩個(gè)函數(shù)的類型是 (Int, Int) -> Int,可以解讀為:
“這個(gè)函數(shù)類型有兩個(gè) Int 型的參數(shù)并返回一個(gè) Int 型的值”。
使用函數(shù)類型
var mathFunction: (Int, Int) -> Int = addTwoInts
注:“定義一個(gè)叫做 mathFunction 的變量,
類型是‘一個(gè)有兩個(gè) Int 型的參數(shù)并返回一個(gè) Int 型的值的函數(shù)’,
并讓這個(gè)新變量指向 addTwoInts 函數(shù)”
調(diào)用
print("Result: \(mathFunction(2, 3))")
// Prints "Result: 5"
函數(shù)類型作為參數(shù)類型
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// 打印“Result: 8”
函數(shù)類型作為返回類型
func stepForward(_ input: Int) -> Int {
return input + 1
}
func stepBackward(_ input: Int) -> Int {
return input - 1
}
例題
eg1:
//此時(shí) Swift 可以自動(dòng)推斷其函數(shù)類型
var op = add //Swift可以推斷出op是一個(gè)函數(shù),函數(shù)類型是(Int, Int) -> Int
print(op(10,30))//
op = minus
print(op(10,30))//minus(10,30)
eg2:
//函數(shù)作為參數(shù)
func printResult(a:Int,b:Int,mathFunc:(Int,Int)->Int){
print(mathFunc(a,b))
}
printResult(a:10,b:20,mathFunc:add)
printResult(a:10,b:20,mathFunc:minus)
eg3:
//函數(shù)作為返回值
func getFunction(a:Int)->(Int,Int)->Int{
if a>10{
return add
}else{
return minus
}
}
print(getFunction(a:12)(10,20))
print(getFunction(a:4)(10,20))