如何在swift

时间:2015-12-22 16:01:38

标签: ios swift

我正在关注斯坦福在线讲座系列,其中教授摧毁了一个计算器应用程序。我发布了下面的viewcontroller.swift文件代码和我当前的main.storyboard的屏幕截图。

我需要知道的是,我应该如何为同一个函数定义多个定义?正如你所看到的,我需要定义一个函数操作,它可能有一个或两个变量作为inout。我通过快速参考了解了为什么我收到此错误here。但是,它没有提到任何接近他所做的事情。我相信这是由于swift版本的一些变化,虽然我不确定。

我浏览了引用并以func funcName(Double ...)格式发现了声明,以传递可变数量的参数,但我不知道如何在这里使用这种实例化。

ViewController.swift:

import UIKit

class ViewController: UIViewController {

@IBOutlet var display: UILabel!

var userIsInTheMiddleOfTyping = false

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func numberPressed(sender: UIButton) {
    // We need to get the value from the current label
    // And then we need to update it with appending the pressed digit at the ending.
    let digit = sender.currentTitle!
    if ( userIsInTheMiddleOfTyping ){
        display.text = display.text! + digit
    } else{
        display.text = digit
        userIsInTheMiddleOfTyping = true
    }
}

@IBAction func operate(sender: UIButton) {
    let operation = sender.currentTitle!
    if userIsInTheMiddleOfTyping{
        enter()
    }
    switch operation {
    case "*": performOperation { $0 * $1 }
    case "/": performOperation { $1 / $0 }
    case "+": performOperation { $0 + $1 }
    case "-": performOperation { $1 - $0 }
    case "sqrt": performOperation( sqrt($0))
    default: break
    }
}

func performOperation( operation: (Double,Double)->Double){
    if operandStack.count >= 2{
        displayValue = operation(operandStack.removeLast() , operandStack.removeLast())
        enter()
    }
}

func performOperation( operation: Double -> Double ){
    if operandStack.count >= 1{
        displayValue = operation(operandStack.removeLast())
        enter()
    }
}

var operandStack = Array<Double>()

@IBAction func enter() {
    userIsInTheMiddleOfTyping = false
    operandStack.append(displayValue)
    print(operandStack)
}
var displayValue: Double{
    get{
        return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
    }
    set{
        display.text = "\(newValue)"
        userIsInTheMiddleOfTyping = false
    }
}

}

Main.StoryBoard: enter image description here

0 个答案:

没有答案