函数声明

来源:互联网 发布:java面向对象的特征 编辑:程序博客网 时间:2024/04/29 13:22
普通函数声明  func 函数名 (参数)->返回值{}
func sayHello(personName: String) -> String {
    let greeting = "Hello, " + personName + "!"    return greeting}


参数可以是变量也可以是另一个函数:

    func performOperation(operation:(Double,Double)->Double){//是一个无返回值得函数,参数类型是<span style="font-family: Arial, Helvetica, sans-serif;">(Double,Double)->Double)</span>        if operandStack.count>=2 {            displayValue = operandStack.removeLast()*operandStack.removeLast()            enter()        }    }        func mulitply(op1:Double,op2:Double)->Double{        return op1*op2    }


    @IBAction func opeate(sender: UIButton) {        let opertation = sender.currentTitle!        if userIsInTheMiddleOfTypeingANumber{            enter()        }        switch opertation {        case "✖️":            performOperation(mulitply) //调用performOperation函数时 参数也是一个函数mulitply//            if operandStack.count>=2 {//displayValue = operandStack.removeLast()*operandStack.removeLast()//                enter()//            }            break        default: break        }    }

以上函数performOperation 还可以写成类似java的写法 这种方法叫colsures 传说中的 闭包

<pre name="code" class="plain">performOperation({    (op1:Double,op2:Double)->Double in    return op1*op2})


closures的语法是

{ ([parameters]) -> [return type] in    [statements]}
反正闭包还是很牛的

具体参考苹果官网的解释


点击打开链接


0 0
原创粉丝点击