Functions
Functions are
self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed.
函數是以一個用來執行特殊任務的自包含代碼塊
Closures:
Closures are
self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
和函數一樣也就是代碼塊,和C,OC裏面的block相似,和其他語言的匿名函數相似
表達式如下:
-
{ (parameters) -> return type in
-
statements
-
}
Global 和nested函數實際上是closure的特例:
Global函數:一個有名字但不獲取任何值的closure
Nested函數:有名字,同時能夠獲取到他們enclosing function裏的值
Closure 式子:一個輕量級語法書寫的沒有名字的closure,同時能夠獲取到他所處的 context中的值
這邊有個例子
//csdn 竟然沒有swift這個語言的標籤==
// 點擊操作按鈕
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if isUserInMiddleOfTypingNumber {
enter()
}
switch operation {
case "×":performOperation { $0 * $1 } // Trailing closure 這邊傳入的其實是 function type 這個nested function就可以直接這麼寫了
case "÷":performOperation { $0 / $1 }
case "+":performOperation { $0 + $1 }
case "−":performOperation { $0 - $1 }
case "√":performOperationSqrt { sqrt($0)}
default: break
}
}
// function type as Parameter Type
func performOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast() , operandStack.removeLast())
enter()
}
}
之前一直看不懂這語法,今天來解釋下
function 和closure分別有Trailing functions 和 Trailing Closures
//含義爲 如果你要傳一個closure expression或 function type給function,當作它最後的一個參數時,你可以這麼寫
func someFunctionThatTakesAClosure(closure: () -> ()) {
// function body goes here
}
// here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure({
// closure's body goes here
})
// here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
// 如果啊 你要傳的這個closure expression是這個function唯一的argument,你連這a pair of parentheses ()都不用寫!!!