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