函數(shù)(Functions)

函數(shù)的概念:

函數(shù)也叫做方法,是有名字的閉包。

函數(shù)的參數(shù):

無參數(shù)
func sayHelloWorld() -> String {
        return "hello, world"
}
print(sayHelloWorld())```
#####有多個(gè)參數(shù)且未定義外部參數(shù)

func sayHello(personName: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return sayHelloAgain(personName)
} else {
return sayHello(personName)
}
}
print(sayHello("Tim", alreadyGreeted: true))
//多個(gè)參數(shù)調(diào)用時(shí),如果沒有聲明外部參數(shù)第一個(gè)參數(shù)不用寫外部參數(shù)。
// Prints "Hello again, Tim!" ```

有多個(gè)參數(shù)并且第一個(gè)參數(shù)定義了外部參數(shù)這時(shí)第一個(gè)參數(shù)的外部參數(shù)不能省略
func sayHello(personName personName: String,alreadyGreeted alreadyGreeted: Bool) -> String {
      if alreadyGreeted {
               return sayHelloAgain(personName)
        } else {
                return sayHello(personName)
 }
 }
 print(sayHello(personName: "Tim", alreadyGreeted: true))
 //多個(gè)參數(shù)調(diào)用時(shí),如果聲明了外部參數(shù)第一個(gè)參數(shù)需要寫外部參數(shù)。
 // Prints "Hello again, Tim!"```
#####有多個(gè)參數(shù)且在參數(shù)名前面加“_”,調(diào)用時(shí)不需要寫外部參數(shù)名

func sayHello(personName: String, _ alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return sayHelloAgain(personName)
} else {
return sayHello(personName)
}
}
print(sayHello("Tim", true))
//多個(gè)參數(shù)調(diào)用時(shí),聲明參數(shù)名前面加“_”,調(diào)用時(shí)不需要寫外部參數(shù)名。
// Prints "Hello again, Tim!"```

帶有默認(rèn)參數(shù)調(diào)用的時(shí)候可以不用傳參則使用默認(rèn)參數(shù)
func someFunction(parameterWithDefault: Int = 12) {
 // function body goes here
 // if no arguments are passed to the function call,
 // value of parameterWithDefault is 12
 }
 someFunction(6) // parameterWithDefault is 6
 someFunction() // parameterWithDefault is 12```
#####可變參數(shù),在參數(shù)類型后面加“...”代表參數(shù)個(gè)數(shù)可變但是每個(gè)函數(shù)最多只有一個(gè)可變參數(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```

函數(shù)通過傳引用,通過在參數(shù)名前面加上inout關(guān)鍵字
func swapTwoInts(inout a: Int, inout _ b: 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"```
####函數(shù)的返回值:
#####因?yàn)楹瘮?shù)沒有返回值所以這里不需要寫返回值得箭頭"->"

func sayGoodbye(personName: String) {
print("Goodbye, (personName)!")
}
sayGoodbye("Dave")
// Prints "Goodbye, Dave!"```

函數(shù)只有一個(gè)返回值
func printAndCount(stringToPrint: String) -> Int {
       print(stringToPrint)
return stringToPrint.characters.count
}
let count = printAndCount("hello, world")
// prints "hello, world" and returns a value of 12```
#####函數(shù)還可以有多個(gè)返回值

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([8, -6, 2, 109, 3, 71])
print("min is (bounds.min) and max is (bounds.max)")
// 通過這樣的方式接收多個(gè)返回值```

函數(shù)有可選返回值時(shí)在返回值括號外加“?”可以返回nil
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)
 }```
####函數(shù)類型:
#####函數(shù)類型和其他類型一樣使用這就意味著函數(shù)可以先聲明再賦值并且讓函數(shù)可以像參數(shù)一樣傳遞,像參數(shù)一樣返回
定義一個(gè)函數(shù)類型為(Int, Int) -> Int的函數(shù)他表示有兩個(gè)Int型參數(shù)和一個(gè)Int型返回值的類型,addTwoInts對mathFunction這個(gè)函數(shù)賦值

func addTwoInts(a: Int, _ b: Int) -> Int {
return a + b
}
var mathFunction: (Int, Int) -> Int = addTwoInts
//函數(shù)類型做為參數(shù)類型使用定義一個(gè)名為mathFunction的參數(shù)的printMathResult函數(shù)并把上文的addTwoInts函數(shù)傳入其中
func printMathResult(mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: (mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// Prints "Result: 8"```

函數(shù)類型做為返回值類型使用
//定義chooseStepFunction函數(shù)它的返回值是一個(gè)參數(shù)為Int返回值為Int的函數(shù)當(dāng)Bool為true時(shí)返回stepBackward 當(dāng)Bool為false時(shí)返回stepForward
 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(currentValue > 0)
        // moveNearerToZero now refers to the stepBackward() function```
####函數(shù)里面定義函數(shù):
Swift在函數(shù)中還可以聲明和調(diào)用函數(shù),如在chooseStepFunction函數(shù)中聲明stepForward函數(shù)和stepBackward函數(shù)。并作為返回值返回

func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backwards ? stepBackward : stepForward
}```

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

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

  • [The Swift Programming Language 中文版]本頁包含內(nèi)容: 函數(shù)是用來完成特定任務(wù)的獨(dú)...
    風(fēng)林山火閱讀 570評論 0 0
  • 函數(shù)是用來完成特定任務(wù)的獨(dú)立的代碼塊??梢越o函數(shù)起一個(gè)名字,用于標(biāo)識一個(gè)函數(shù),當(dāng)函數(shù)需要執(zhí)行的時(shí)候,這個(gè)名字就會用...
    EndEvent閱讀 792評論 1 3
  • 86.復(fù)合 Cases 共享相同代碼塊的多個(gè)switch 分支 分支可以合并, 寫在分支后用逗號分開。如果任何模式...
    無灃閱讀 1,559評論 1 5
  • 多重返回值函數(shù) 你可以用元組(tuple)類型讓多個(gè)值作為一個(gè)復(fù)合值從函數(shù)中返回。 下例中定義了一個(gè)名為 minM...
    雨影閱讀 181評論 0 0
  • 本頁包含內(nèi)容:- 函數(shù)定義與調(diào)用- 函數(shù)參數(shù)與返回值- 函數(shù)參數(shù)標(biāo)簽和參數(shù)名稱- 函數(shù)類型- 嵌套函數(shù) ** 1、...
    平凡之路561閱讀 203評論 0 0

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