Swift学习笔记(8)--函数
1.定義及調(diào)用
func sayHelloAgain(personName: String) -> String {return "Hello again, " + personName + "!" } println(sayHelloAgain("Anna")) //Hello again, Anna!
2.函數(shù)分類
//1.普通函數(shù)(略)//2.無參函數(shù) func sayHelloWorld() -> String {return "hello, world" }//3.無返回值函數(shù) func sayHelloWorld(){println("hello, world") }//4.多參數(shù)函數(shù) func add(start: Int, end: Int) -> Int {return end + start }//5.多返回值函數(shù)//例子:統(tǒng)計一個字符串中元音輔音的數(shù)量 func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {var vowels = 0, consonants = 0, others = 0for character in string {switch String(character).lowercaseString {case "a", "e", "i", "o", "u":++vowelscase "b", "c", "d", "f", "g", "h", "j", "k", "l", "m","n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":++consonantsdefault:++others}}return (vowels, consonants, others) }let total = count("some arbitrary string!") println("\(total.vowels) vowels and \(total.consonants) consonants") //6 vowels and 13 consonants
3.外部參數(shù)名
局部參數(shù)名(local parameter name),只能在函數(shù)體中使用
外部參數(shù)名(External Parameter Names),函數(shù)的使用者在調(diào)用函數(shù)時提供參數(shù)名字
與OC類似,swift提供了外部參數(shù)名的定義方法:
//1.顯示定義外部參數(shù)名 func join(firstName s1: String,lastName s2: String, middleName s3:String) {println("The name is :\(s1) \(s3) \(s2)") }join(firstName: "Jason", lastName: "Wood", middleName: "Hasen")//2.隱式定義外部參數(shù)名,使用 # + 參數(shù)名 func join2(#firstName: String,#lastName: String, #middleName:String) {println("The name is :\(firstName) \(middleName) \(lastName)") } join2(firstName: "Jason", lastName: "Wood", middleName: "Hasen")
4.默認(rèn)參數(shù)值
在函數(shù)定義時可以提供一個默認(rèn)的參數(shù)值
func join(string s1: String, toString s2: String, withJoiner joiner: String = "-") -> String {return s1 + joiner + s2 } println(join(string: "hello", toString:"world")) //hello-world
為了使定義外部參數(shù)名更加簡單,當(dāng)你未給帶默認(rèn)值的參數(shù)提供外部參數(shù)名時,Swift 會自動提供外部名字。此時外部參數(shù)名與局部名字是一樣的,就像你已經(jīng)在局部參數(shù)名前寫了井號(#)一樣。
func join(s1: String, s2: String, joiner: String = " ") -> String {return s1 + joiner + s2 } println(join("hello", "world", joiner: "-")) //hello-world
5.可變參數(shù)(Variadic Parameters)
一個可變參數(shù)(variadic parameter)可以接受一個或多個值。函數(shù)調(diào)用時,你可以用可變參數(shù)來傳入不確定數(shù)量的輸入?yún)?shù)。通過在變量類型名后面加入(...)的方式來定義可變參數(shù)。
注:一個函數(shù)至多能有一個可變參數(shù),而且它必須是參數(shù)表中最后的一個。這樣做是為了避免函數(shù)調(diào)用時出現(xiàn)歧義。
func arithmeticMean(numbers: Double...) -> Double {var total: Double = 0for number in numbers {total += number}return total / Double(numbers.count) } println("平均值為:\(arithmeticMean(1, 2, 3, 4, 5))") //平均值為:3.0
6.常量參數(shù)和變量參數(shù)(Constant and Variable Parameters)
函數(shù)參數(shù)默認(rèn)是常量。試圖在函數(shù)體中更改參數(shù)值將會導(dǎo)致編譯錯誤。這意味著你不能錯誤地更改參數(shù)值。
但是,有時候,如果函數(shù)中有傳入?yún)?shù)的變量值副本將是很有用的。你可以通過指定一個或多個參數(shù)為變量參數(shù),從而避免自己在函數(shù)中定義新的變量。變量參數(shù)不是常量,你可以在函數(shù)中把它當(dāng)做新的可修改副本來使用。
通過在參數(shù)名前加關(guān)鍵字?var?來定義變量參數(shù):
func changeValue(var x:Int){x = 12 //如果不定義var,此處語句會報錯 }//函數(shù)內(nèi)部的參數(shù)變化是副本值的變化,函數(shù)外部的值不受影響 var y = 0 changeValue(y) println(y) //還是0
7.輸入輸出參數(shù)(In-Out Parameters)
變量參數(shù),正如上面所述,僅僅能在函數(shù)體內(nèi)被更改。如果你想要一個函數(shù)可以修改參數(shù)的值,并且想要在這些修改在函數(shù)調(diào)用結(jié)束后仍然存在,那么就應(yīng)該把這個參數(shù)定義為輸入輸出參數(shù)(In-Out Parameters)。
定義一個輸入輸出參數(shù)時,在參數(shù)定義前加?inout?關(guān)鍵字。一個輸入輸出參數(shù)有傳入函數(shù)的值,這個值被函數(shù)修改,然后被傳出函數(shù),替換原來的值。
你只能傳入一個變量作為輸入輸出參數(shù)。你不能傳入常量或者字面量(literal value),因為這些量是不能被修改的。當(dāng)傳入的參數(shù)作為輸入輸出參數(shù)時,需要在參數(shù)前加&符,表示這個值可以被函數(shù)修改。
注:輸入輸出參數(shù)不能有默認(rèn)值,而且可變參數(shù)不能用?inout?標(biāo)記。如果你用?inout?標(biāo)記一個參數(shù),這個參數(shù)不能被?var?或者?let?標(biāo)記。
func changeValue2(inout x:Int){x = 12 }var y = 0 //inout傳入的參數(shù)只能是變量 changeValue2(&y) //需要在參數(shù)前加 & 來標(biāo)記是inout參數(shù) println(y) //此時打印出來的是修改后的值 12
8.函數(shù)類型(Function Types)
每個函數(shù)都有種特定的函數(shù)類型,由函數(shù)的參數(shù)類型和返回類型組成。
比如下面兩個函數(shù)的函數(shù)類型就是(Int, Int) -> Int,?可以讀作“有兩個?Int?型的參數(shù)并返回一個?Int?型的值。”
func addTwoInts(a: Int, b: Int) -> Int {return a + b } func multiplyTwoInts(a: Int, b: Int) -> Int {return a * b }而對于無參數(shù)和無返回值的函數(shù)類型為() -> (),叫“沒有參數(shù),并返回?Void?類型的函數(shù)。”。沒有指定返回類型的函數(shù)總返回Void。在Swift中,Void?與空的元組是一樣的。
使用舉例:
func addTwoInts(a: Int, b: Int) -> Int {return a + b } func multiplyTwoInts(a: Int, b: Int) -> Int {return a * b }//定義 var mathFunction: (Int, Int) -> Int = addTwoInts//調(diào)用與函數(shù)調(diào)用一樣 println("Result: \(mathFunction(2, 3))") //Result: 5//相同匹配類型的不同函數(shù)可以被賦值給同一個變量 mathFunction = multiplyTwoInts println("Result: \(mathFunction(2, 3))") //Result: 6//當(dāng)賦值一個函數(shù)給常量或變量時,沒有定義函數(shù)類型, Swift會自動推斷其函數(shù)類型 let anotherMathFunction = addTwoInts //anotherMathFunction 此時的函數(shù)類型就是 (Int, Int) -> Int println("Result: \(anotherMathFunction(3, 4))") //Result: 7//函數(shù)類型作為參數(shù)類型 func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {println("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 } func chooseStepFunction(backwards: Bool) -> (Int) -> Int {return backwards ? stepBackward : stepForward //根據(jù)條件返回不同的函數(shù)類型 }var currentValue = 3 let moveNearerToZero = chooseStepFunction(currentValue > 0) //獲取函數(shù)類型 let result = moveNearerToZero(currentValue) //根據(jù)函數(shù)類型,得到結(jié)果 println(result) //2
9.嵌套函數(shù)(Nested Functions)
把函數(shù)定義在別的函數(shù)體中,稱作嵌套函數(shù)(nested functions)。
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 } var currentValue = -4 let moveNearerToZero = chooseStepFunction(currentValue > 0) let result = moveNearerToZero(currentValue) //根據(jù)函數(shù)類型,得到結(jié)果 println(result) //-3
轉(zhuǎn)載于:https://www.cnblogs.com/anywherego/p/3789267.html
總結(jié)
以上是生活随笔為你收集整理的Swift学习笔记(8)--函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。