Swift-函數(shù)

官方文檔

定義和調(diào)用函數(shù)

定義:

func greet(person: String) -> String {
    let greeting = "Hello, " + person + "!"
    return greeting
}

調(diào)用:

print(greet(person: "Anna"))
// Prints "Hello, Anna!"
print(greet(person: "Brian"))
// Prints "Hello, Brian!"
func greetAgain(person: String) -> String {
    return "Hello again, " + person + "!"
}
print(greetAgain(person: "Anna"))
// Prints "Hello again, Anna!"

函數(shù)參數(shù)和返回值

沒有參數(shù)的函數(shù)

返回值為字符串的值

func sayHelloWorld() -> String {
    return "hello, world"
}
print(sayHelloWorld())
// Prints "hello, world"

具有多個參數(shù)的函數(shù)

一個參數(shù)名person 類型為字符串,另一個alreadyGreeted 類型為bool 返回一個字符串

func greet(person: String, alreadyGreeted: Bool) -> String {
    if alreadyGreeted {
        return greetAgain(person: person)
    } else {
        return greet(person: person)
    }
}
print(greet(person: "Tim", alreadyGreeted: true))
// Prints "Hello again, Tim!"

沒有返回值的函數(shù)
func greet(person: String) {
    print("Hello, \(person)!")
}
greet(person: "Dave")
// Prints "Hello, Dave!"

由于該函數(shù)的定義不需要返回值,因此它不包含返回箭頭(->)或返回類型
調(diào)用函數(shù)時脯颜,可以忽略其返回值:

func printAndCount(string: String) -> Int {
    print(string)
    return string.count
}
func printWithoutCounting(string: String) {
    let _ = printAndCount(string: string)
}
printAndCount(string: "hello, world")
// prints "hello, world" and returns a value of 12
printWithoutCounting(string: "hello, world")
// prints "hello, world" but does not return a value
具有多個返回值的函數(shù)

返回兩個返回值处坪,最大最小

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)
}
let bounds = minMax(array: [8, -6, 2, 109, 3, 71])
print("min is \(bounds.min) and max is \(bounds.max)")
// Prints "min is -6 and max is 109"

可選的元組返回類型
func minMax(array: [Int]) -> (min: Int, max: Int)? {
    if array.isEmpty { return nil }
    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)
}
if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
    print("min is \(bounds.min) and max is \(bounds.max)")
}
// Prints "min is -6 and max is 109"
隱式返回函數(shù)
func greeting(for person: String) -> String {
    "Hello, " + person + "!"
}
print(greeting(for: "Dave"))
// Prints "Hello, Dave!"

func anotherGreeting(for person: String) -> String {
    return "Hello, " + person + "!"
}
print(anotherGreeting(for: "Dave"))
// Prints "Hello, Dave!"

 func greeting(for person: String) -> String {
        "Hello, " + person + "!"
    }

 func greeting1(person: String) -> String {
          "Hello, " + person + "!"
      }
image.png

函數(shù)參數(shù)標(biāo)簽和參數(shù)名稱

func someFunction(firstParameterName: Int, secondParameterName: Int) {
    // In the function body, firstParameterName and secondParameterName
    // refer to the argument values for the first and second parameters.
}
someFunction(firstParameterName: 1, secondParameterName: 2)

指定參數(shù)標(biāo)簽
func someFunction(argumentLabel parameterName: Int) {
    // In the function body, parameterName refers to the argument value
    // for that parameter.
}

func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)!  Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
// Prints "Hello Bill!  Glad you could visit from Cupertino."

image.png

在參數(shù)前面加from 和for類似 隱式參數(shù)

省略參數(shù)標(biāo)簽
func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
    // In the function body, firstParameterName and secondParameterName
    // refer to the argument values for the first and second parameters.
}

someFunction(1, secondParameterName: 2)

在參數(shù)名前面加_ 的時候 在函數(shù)調(diào)用的時候 參數(shù)名可以省略

默認(rèn)參數(shù)值
func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
    // If you omit the second argument when calling this function, then
    // the value of parameterWithDefault is 12 inside the function body.
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault is 6
someFunction(parameterWithoutDefault: 4) // parameterWithDefault is 12

如果是參數(shù)有默認(rèn)值 那么驾茴,調(diào)用的時候可以 默認(rèn)的參數(shù)可以 忽略
someFunction(parameterWithoutDefault: 4)
如果都傳了參數(shù) 值那么 會按照 最新傳入的值進(jìn)行運算

可變參數(shù)
func arithmeticMean(_ numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers

求和锅必,numbers: Double... 寫法我現(xiàn)在也沒搞明白為嘛這么寫

輸入輸出參數(shù)
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)")
// Prints "someInt is now 107, and anotherInt is now 3"


image.png

如果用inout修飾那么 必須要有 &來獲取參數(shù)的值
傳入一個參數(shù)事格,調(diào)用函數(shù)后惕艳,返回一個 “&參數(shù)”的值

函數(shù)類型

使用函數(shù)類型
func addTwoInts(_ a: Int, _ b: Int) -> Int {
    return a + b
}
func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
    return a * b
}

函數(shù)類型作為參數(shù)類型
var mathFunction: (Int, Int) -> Int = addTwoInts

image.png

定義一個方法搞隐,打印出來如上是function

mathFunction = multiplyTwoInts
print("Result: \(mathFunction(2, 3))")
// Prints "Result: 6"

函數(shù)類型作為返回類型
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// Prints "Result: 8"

image.png

函數(shù)作為一個參數(shù),

函數(shù)類型作為返回類型
func stepForward(_ input: Int) -> Int {
    return input + 1
}
func stepBackward(_ input: Int) -> Int {
    return input - 1
}

func chooseStepFunction(backward: Bool) -> (Int) -> Int {
    return backward ? stepBackward : stepForward
}

var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero now refers to the stepBackward() function

print("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// 3...
// 2...
// 1...
// zero!

嵌套函數(shù)
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
    func stepForward(input: Int) -> Int { return input + 1 }
    func stepBackward(input: Int) -> Int { return input - 1 }
    return backward ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!
image.png

返回的類型是函數(shù)類型 函數(shù)的的返回值的類型是 整形

OK
本期的 Swift-函數(shù)就到這里远搪。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末劣纲,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子谁鳍,更是在濱河造成了極大的恐慌癞季,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,589評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件倘潜,死亡現(xiàn)場離奇詭異绷柒,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)涮因,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,615評論 3 396
  • 文/潘曉璐 我一進(jìn)店門废睦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人养泡,你說我怎么就攤上這事嗜湃∧斡Γ” “怎么了?”我有些...
    開封第一講書人閱讀 165,933評論 0 356
  • 文/不壞的土叔 我叫張陵购披,是天一觀的道長杖挣。 經(jīng)常有香客問我,道長刚陡,這世上最難降的妖魔是什么惩妇? 我笑而不...
    開封第一講書人閱讀 58,976評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮筐乳,結(jié)果婚禮上屿附,老公的妹妹穿的比我還像新娘。我一直安慰自己哥童,他們只是感情好挺份,可當(dāng)我...
    茶點故事閱讀 67,999評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著贮懈,像睡著了一般匀泊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上朵你,一...
    開封第一講書人閱讀 51,775評論 1 307
  • 那天各聘,我揣著相機(jī)與錄音,去河邊找鬼抡医。 笑死躲因,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的忌傻。 我是一名探鬼主播大脉,決...
    沈念sama閱讀 40,474評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼水孩!你這毒婦竟也來了镰矿?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,359評論 0 276
  • 序言:老撾萬榮一對情侶失蹤俘种,失蹤者是張志新(化名)和其女友劉穎秤标,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體宙刘,經(jīng)...
    沈念sama閱讀 45,854評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡苍姜,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,007評論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了悬包。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片衙猪。...
    茶點故事閱讀 40,146評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出屈嗤,到底是詐尸還是另有隱情潘拨,我是刑警寧澤,帶...
    沈念sama閱讀 35,826評論 5 346
  • 正文 年R本政府宣布饶号,位于F島的核電站铁追,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏茫船。R本人自食惡果不足惜琅束,卻給世界環(huán)境...
    茶點故事閱讀 41,484評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望算谈。 院中可真熱鬧涩禀,春花似錦、人聲如沸然眼。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,029評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽高每。三九已至屿岂,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間鲸匿,已是汗流浹背爷怀。 一陣腳步聲響...
    開封第一講書人閱讀 33,153評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留带欢,地道東北人运授。 一個月前我還...
    沈念sama閱讀 48,420評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像乔煞,于是被迫代替她去往敵國和親吁朦。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,107評論 2 356