Swift 代码分享——Calculator without MVC

最近在跟着斯坦福的网易公开课教程自学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
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值