函數(shù)是一個(gè)獨(dú)立的代碼塊绘沉,用來(lái)執(zhí)行特定的任務(wù)枉阵。通過(guò)給函數(shù)一個(gè)名字來(lái)定義它的功能,并且在需要的時(shí)候铛铁,通過(guò)這個(gè)名字來(lái)“調(diào)用”函數(shù)執(zhí)行它的任務(wù)。
函數(shù)的形式參數(shù)和返回值
在 Swift 中却妨,函數(shù)的形式參數(shù)和返回值非常靈活饵逐。你可以定義從一個(gè)簡(jiǎn)單的只有一個(gè)未命名形式參數(shù)的工具函數(shù)到那種具有形象的參數(shù)名稱和不同的形式參數(shù)選項(xiàng)的復(fù)雜函數(shù)之間的任何函數(shù)。
有返回值
func sayHelloWorld() -> String {
return "hello, world"
}
形參默認(rèn)是let
彪标,也只能是let
無(wú)返回值
func sayHelloWorld() -> Void {
print("hello, world")
}
func sayHelloWorld() -> () {
print("hello, world")
}
func sayHelloWorld(){
print("hello, world")
}
隱式返回
如果整個(gè)函數(shù)體是一個(gè)單一表達(dá)式倍权,那么函數(shù)隱式返回這個(gè)表達(dá)式。也就是函數(shù)只有一個(gè)表達(dá)式的時(shí)候捐下,不用return
func sum(v1:Int,v2:Int) -> Int {
v1+v2
}
print(sum(v1: 1, v2: 2))
返回元組:實(shí)現(xiàn)多返回值
為了讓函數(shù)返回多個(gè)值作為一個(gè)復(fù)合的返回值账锹,你可以使用元組類型作為返回類型。
func minMax(array: [Int]) -> (min: Int, max: Int) {
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
函數(shù)的文檔注釋
/// 求和【概述】
/// - Parameter v1: 第一個(gè)整數(shù)
/// - Parameter v2: 第二個(gè)整數(shù)
/// - Note:傳入兩個(gè)整數(shù)即可【批注】
func sum(v1:Int,v2:Int) -> Int {
v1+v2
}
參數(shù)標(biāo)簽
每一個(gè)函數(shù)的形式參數(shù)都包含實(shí)際參數(shù)標(biāo)簽和形式參數(shù)名坷襟。實(shí)際參數(shù)標(biāo)簽用在調(diào)用函數(shù)的時(shí)候奸柬;在調(diào)用函數(shù)的時(shí)候每一個(gè)實(shí)際參數(shù)前邊都要寫實(shí)際參數(shù)標(biāo)簽。形式參數(shù)名用在函數(shù)的實(shí)現(xiàn)當(dāng)中婴程。默認(rèn)情況下廓奕,形式參數(shù)使用它們的形式參數(shù)名作為實(shí)際參數(shù)標(biāo)簽。
func goToWork(time:String) {
print("this time is \(time)")
}
goToWork(time: "10點(diǎn)")
func goToWork(at time:String) {
print("this time is \(time)")
}
goToWork(at: "10點(diǎn)")
可以使用下劃線_
省略參數(shù)標(biāo)簽
func sum(_ v1:Int, _ v2:Int) -> Int {
v1 + v2
}
sum(10, 20)
默認(rèn)參數(shù)值
你可以通過(guò)在形式參數(shù)類型后給形式參數(shù)賦一個(gè)值來(lái)給函數(shù)的任意形式參數(shù)定義一個(gè)默認(rèn)值档叔。如果定義了默認(rèn)值桌粉,你就可以在調(diào)用函數(shù)時(shí)候省略這個(gè)形式參數(shù)。
把不帶有默認(rèn)值的形式參數(shù)放到函數(shù)的形式參數(shù)列表中帶有默認(rèn)值的形式參數(shù)前邊衙四,不帶有默認(rèn)值的形式參數(shù)通常對(duì)函數(shù)有著重要的意義——把它們寫在前邊可以便于讓人們看出來(lái)無(wú)論是否省略帶默認(rèn)值的形式參數(shù)铃肯,調(diào)用的都是同一個(gè)函數(shù)。
func check(name:String = "tom",age:Int,job:String = "none"){
print("name is \(name),age is \(age), job is \(job)")
}
check(age: 10)
check(name: "kk", age: 20, job: "IT")
check(name: "aa", age: 30)
check(age: 25, job: "Teacher")
可變參數(shù)
一個(gè)可變形式參數(shù)可以接受零或者多個(gè)特定類型的值传蹈。當(dāng)調(diào)用函數(shù)的時(shí)候你可以利用可變形式參數(shù)來(lái)聲明形式參數(shù)可以被傳入值的數(shù)量是可變的押逼。可以通過(guò)在形式參數(shù)的類型名稱后邊插入三個(gè)點(diǎn)符號(hào)( ...)來(lái)書寫可變形式參數(shù)惦界。
func sum(_ numbers:Int...) -> Int{
var total = 0
for item in numbers {
total += item
}
return total
}
Swift自帶的print函數(shù)
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
public func print(_ items: Any..., separator: String = " ", terminator: String = "\n")
- 第一個(gè)參數(shù):就是需要打印的值挑格,是一個(gè)可變參數(shù)
- 第二個(gè)參數(shù):兩個(gè)打印值連接的地方,默認(rèn)是空格
- 第三個(gè)參數(shù):結(jié)尾默認(rèn)是
\n
換行
輸入輸出參數(shù)
可變形式參數(shù)只能在函數(shù)的內(nèi)部做改變沾歪。如果你想函數(shù)能夠修改一個(gè)形式參數(shù)的值漂彤,而且你想這些改變?cè)诤瘮?shù)結(jié)束之后依然生效,那么就需要將形式參數(shù)定義為輸入輸出形式參數(shù)。
在形式參數(shù)定義開始的時(shí)候在前邊添加一個(gè) inout關(guān)鍵字可以定義一個(gè)輸入輸出形式參數(shù)挫望。輸入輸出形式參數(shù)有一個(gè)能輸入給函數(shù)的值立润,函數(shù)能對(duì)其進(jìn)行修改,還能輸出到函數(shù)外邊替換原來(lái)的值士骤。
你只能把變量作為輸入輸出形式參數(shù)的實(shí)際參數(shù)范删。你不能用常量或者字面量作為實(shí)際參數(shù),因?yàn)槌A亢妥置媪坎荒苄薷目郊 T趯⒆兞孔鳛閷?shí)際參數(shù)傳遞給輸入輸出形式參數(shù)的時(shí)候到旦,直接在它前邊添加一個(gè)和符號(hào) ( &) 來(lái)明確可以被函數(shù)修改。
var b = 10
func test(a:inout Int) {
a = 20
}
test(a: &b)
print(b) //20
可以用inout
定義一個(gè)輸入輸出參數(shù):可以在函數(shù)內(nèi)部修改外部實(shí)參的值
- 可變參數(shù)不能標(biāo)記為
inout
-
inout
參數(shù)不能有默認(rèn)值 -
inout
參數(shù)只能傳入可以被多次賦值的 -
inout
參數(shù)的本質(zhì)就是地址傳遞
函數(shù)重載
規(guī)則
- 函數(shù)名相同
- 參數(shù)個(gè)數(shù)不同或者參數(shù)類型不同或者參數(shù)標(biāo)簽不同
func sum(v1:Int,v2:Int) -> Int {
v1+v2
}
func sum(_ v1:Int, _ v2:Int) -> Int {
v1 + v2
}
func sum(v1:String,v2:String) -> String {
v1 + v2
}
func sum(v1:Int, v2:Int, v3:Int) -> Int {
v1 + v2 + v3
}
內(nèi)聯(lián)函數(shù)
- 如果開啟了編譯器優(yōu)化(Release默認(rèn)開始優(yōu)化)巨缘,編譯器回自動(dòng)將某些函數(shù)變成內(nèi)聯(lián)函數(shù)
- 內(nèi)聯(lián)函數(shù)就是把函數(shù)調(diào)用添忘,展開成函數(shù)題
//開啟前
func test() {
print("內(nèi)聯(lián)函數(shù)")
}
test()
//開啟后
print("內(nèi)聯(lián)函數(shù)")
哪些函數(shù)不會(huì)被自動(dòng)內(nèi)聯(lián)
- 1、函數(shù)體比較長(zhǎng)
- 2若锁、包含遞歸調(diào)用
- 3搁骑、包含動(dòng)態(tài)派發(fā)
函數(shù)類型
每一個(gè)函數(shù)都有一個(gè)特定的函數(shù)類型,它由形式參數(shù)類型又固,返回類型組成仲器。
你可以像使用 Swift 中的其他類型一樣使用函數(shù)類型。例如仰冠,你可以給一個(gè)常量或變量定義一個(gè)函數(shù)類型乏冀,并且為變量指定一個(gè)相應(yīng)的函數(shù)。
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
var mathFunction: (Int, Int) -> Int = addTwoInts
print(mathFunction(1,2))
這可以讀作:
定義一個(gè)叫做 mathFunction
的變量洋只,它的類型是一個(gè)能接受兩個(gè) Int值的函數(shù)辆沦,并返回一個(gè) Int值。
將這個(gè)新的變量指向 addTwoInts
函數(shù)识虚。
函數(shù)類型可以作為函數(shù)的參數(shù)
func sum(a:Int,b:Int) -> Int {
a + b
}
func reduction(a:Int,b:Int) -> Int {
a - b
}
func printResult(_ mathFn:(Int,Int) -> Int, a:Int, b:Int) {
print(mathFn(a,b))
}
printResult(sum, a: 3, b: 2)
printResult(reduction, a: 3, b: 2)
函數(shù)類型作為函數(shù)返回值
func next(_ input:Int) -> Int {
input + 1
}
func previous(_ input:Int) -> Int {
input - 1
}
func forward(_ forward:Bool) -> (Int) -> Int {
forward ? next : previous
}
print(forward(true)(3)) // 4
print(forward(false)(3)) // 2
返回值是函數(shù)類型的函數(shù)叫做高階函數(shù)
typealias別名
按照swift標(biāo)準(zhǔn)庫(kù)的定義Void
就是一個(gè)空元組
public typealias Void = ()
我們知道swift中沒(méi)有byte肢扯、short、Long
類型担锤,如果我們想要這樣的類型蔚晨,就可以用typealias
實(shí)現(xiàn)
typealias Byte = Int8
typealias Short = Int16
typealias Long = Int64
我們還可以給函數(shù)起一個(gè)別名
typealias IntFn = (Int,Int) -> Int
func difference(v1:Int,v2:Int) -> Int {
v1 - v2
}
let fn:IntFn = difference
print(fn(2,1)) //1
我們還可以給元組起別名
typealias Date = (year:Int,month:Int,day:Int)
func test(_ date:Date) {
print(date.year)
}
test((2019,10,30))
嵌套函數(shù)
將函數(shù)定義在函數(shù)的內(nèi)部
func forward(_ forward:Bool) -> (Int) -> Int {
func next(_ input:Int) -> Int {
input + 1
}
func previous(_ input:Int) -> Int {
input - 1
}
return forward ? next : previous
}