Swift Function & Closure
Functions Functionsare 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. 函数是以一个用来执行特殊任务的自包含代码块 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID158
Closures: Closuresare 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相似,和其他语言的匿名函数相似
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID94 表达式如下:
Global 和nested函数实际上是closure的特例:
这边有个例子 //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
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 ofparentheses ()都不用写!!! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |