2020-03-25 Swift之函數(shù)

函數(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))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容