標籤:swift
函數函數的定義、參數、傳回值
func sayHello(personName: String) -> String { let greeting = "Hello, " + personName + "!" return greeting}
可以省略參數和傳回值
func sayGoodbye(personName: String) { println("Goodbye, \(personName)!")}
也可以包含多個參數和多個傳回值
func count(string1: String, string2: String) -> (vowels: Int, consonants: Int, others: Int) { var vowels = 0, consonants = 0, others = 0 for character in string1 { switch String(character).lowercaseString { case "a", "e", "i", "o", "u": ++vowels case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": ++consonants default: ++others } } return (vowels, consonants, others)}
多重傳回值返回的是一個元祖,沒有傳回值時其實返回的是Void,一個空的元祖
參數名
參數名一般只能函數內部使用,但為了使語言表達更清晰,可以定義外部參數名,使用這些外部參數名使代碼更易閱讀
func join(string s1: String, toString s2: String, withJoiner joiner: String) -> String { return s1 + joiner + s2}join(string: "hello", toString: "world", withJoiner: ", ")
外部名可以與內部名保持一致
func containsCharacter(#string: String, #characterToFind: Character) -> Bool { for character in string { if character == characterToFind { return true } } return false}let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v")
函數參數可以提供預設值
func join(string s1: String, toString s2: String, withJoiner joiner: String = " ") -> String { return s1 + joiner + s2}join(string: "hello", toString:"world")// returns "hello world"join(string: "hello", toString: "world", withJoiner: "-")// returns "hello-world"
對提供了預設值的參數,參數名自動表示為內部名和外部名
輸入輸出參數inout
,表示參數可以被函數體修改,並保留給外部繼續使用
func swapTwoInts(inout a: Int, inout b: Int) { let temporaryA = a a = b b = temporaryA}
調用時需要在參數前加&
var someInt = 3var anotherInt = 107swapTwoInts(&someInt, &anotherInt)
函數類型
函數類型由參數類型和傳回值類型共同決定,類似c語言的函數指標
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 = addTwoIntsprintln("Result: \(mathFunction(2, 3))")mathFunction = multiplyTwoIntsprintln("Result: \(mathFunction(2, 3))")
函數類型與其他類型一樣,可以做參數,也可以做傳回值
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 = 3let moveNearerToZero = chooseStepFunction(currentValue > 0)
函數可以嵌套
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}
閉包
閉包特性應用在嵌套函數和閉包運算式中,是一種函數式編程特性
閉包運算式
一般形式如下
{ (parameters) -> returnType in statements}
例如
reversed = sorted(names, { (s1: String, s2: String) -> Bool in return s1 > s2})// 閉包可以類型推斷,所以可以簡化為reversed = sorted(names, { s1, s2 in return s1 > s2 } )// 單行運算式可以省略返回的returnreversed = sorted(names, { s1, s2 in s1 > s2 } )// 還可以縮寫參數reversed = sorted(names, { $0 > $1 } )
如果閉包函數很長,為了增強可讀性,可以講閉包函數放到()外邊緊跟函數調用,
func someFunctionThatTakesAClosure(closure: () -> ()) { // 函數體部分}// 以下是使用尾隨閉包進行函數調用someFunctionThatTakesAClosure() { // 閉包主體部分}
捕獲值
閉包可以在其定義的上下文中捕獲常量或變數。 即使定義這些常量和變數的原域已經不存在,閉包仍然可以在閉包函數體內引用和修改這些值。
func makeIncrementor(forIncrement amount: Int) -> () -> Int { var runningTotal = 0 func incrementor() -> Int { runningTotal += amount return runningTotal } return incrementor}let incrementByTen = makeIncrementor(forIncrement: 10)incrementByTen()// 返回的值為10incrementByTen()// 返回的值為20incrementByTen()// 返回的值為30
Swift入門(二)