最近在跟着斯坦福的网易公开课教程自学Swift, 跟着做计算器以学习语法,第三讲中即将将计算器改成MVC版本,所以就先贴出未经过MVC分离的代码,权当学习记录.
已调试通过,跟课堂上的一样,enter压栈,操作符运算
注释后续补上:)
//
// ViewController.swift
// CalculatorGerry
//
// Created by GerryKe on 15/5/21.
// Copyright (c) 2015年 <span style="font-family: Arial, Helvetica, sans-serif;">GerryKe</span>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var DigitDisplay: UILabel!
var IsTyped = false
@IBAction func AppenDigit(sender: UIButton) {
let digit = sender.currentTitle!
if(IsTyped){
DigitDisplay.text = DigitDisplay.text! + digit
}
else{
DigitDisplay.text = digit
IsTyped = true
}
}
@IBAction func OperratorCalc(sender: UIButton) {
if(IsTyped){
PutIntoStack()
}
switch(sender.currentTitle!){
case "✕": ControlWhenCalc({$0 * $1})
case "÷": ControlWhenCalc({$1 / $0})
case "−": ControlWhenCalc({$1 - $0})
case "+": ControlWhenCalc({$0 + $1})
case "√": ControlWhenCalc({sqrt($0)})
default:break
}
}
private func ControlWhenCalc(oper:(Double, Double)->Double){
if(DigitStack.count >= 2){
DisplayValue = oper(DigitStack.removeLast(), DigitStack.removeLast())
println("\(DigitStack)")
}
}
private func ControlWhenCalc(oper:Double->Double){
if(DigitStack.count >= 1){
DisplayValue = oper(DigitStack.removeLast())
println("\(DigitStack)")
}
}
var DigitStack = Array<Double>()
@IBAction func PutIntoStack() {
IsTyped = false
DigitStack.append(DisplayValue)
println("\(DigitStack)")
}
var DisplayValue: Double {
get{
return NSNumberFormatter().numberFromString(DigitDisplay.text!)!.doubleValue
}
set{
DigitDisplay.text = "\(newValue)"
IsTyped = false
}
}
}