本文利用ios实现计算器app,后期将用mvc结构重构

import UIKit

class CalculViewController: UIViewController {

    @IBOutlet weak var display: UILabel!

    var userIsInTheMiddleOFTypingANumber:Bool=false

    @IBAction func appendDigit(sender: UIButton) {
let digit=sender.currentTitle!
if userIsInTheMiddleOFTypingANumber {
display.text=display.text!+digit
}else{
display.text=digit
userIsInTheMiddleOFTypingANumber=true
}
}
var operandstack:Array<Double>=Array<Double>() @IBAction func operate(sender: UIButton) {
let operation=sender.currentTitle!;
if userIsInTheMiddleOFTypingANumber {
enter()
}
switch operation {
case "×":performeOperation{$0*$1}
case "÷":performeOperation{$1/$0}
case "+":performeOperation{$0+$1}
case "-":performeOperation{$1-$0}
case "√":performeOperation{sqrt($0)}
default:
break
} } // func multiply(op1:Double,op2:Double) -> Double {
// return op1*op2;
// } func performeOperation(operation:(Double,Double)->Double){
if operandstack.count>=2 {
displayValue=operation(operandstack.removeLast(),operandstack.removeLast())
enter()
} } private func performeOperation(operation:Double->Double){
if operandstack.count>=1 {
displayValue=operation(operandstack.removeLast())
enter()
} } @IBAction func enter() {
userIsInTheMiddleOFTypingANumber=false
operandstack.append(displayValue)
print("operandstack=\(operandstack)") } var displayValue:Double{
get{
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set{
display.text="\(newValue)"
userIsInTheMiddleOFTypingANumber=false
}
}

知识点如下

  • 计算型属性的setter与getter
  • swift利用函数作为参数
  • swift的重载,详情参见:swift override

效果如下

增加model文件

import Foundation

class CalculatorBrain {
private enum Op : CustomStringConvertible{
case operand(Double)
case UnaryOperation(String,Double->Double)
case BinaryOperation(String,(Double,Double)->Double) var description:String{
get{
switch self {
case .operand(let operand):
return "\(operand)"
case .BinaryOperation(let symbol,_):
return symbol
case .UnaryOperation(let symbol, _):
return symbol }
} } } private var opstack=[Op]()
private var knowOps=[String:Op]() init(){
func learnOp(op:Op){
knowOps[op.description]=op
}
learnOp(Op.BinaryOperation("×"){$0*$1})
learnOp(Op.BinaryOperation("÷"){$1/$0})
learnOp(Op.BinaryOperation("+"){$0+$1})
learnOp(Op.BinaryOperation("-"){$1-$0})
learnOp(Op.UnaryOperation("√"){sqrt($0)})
// knowOps["×"]=Op.BinaryOperation("×"){$0*$1}
// knowOps["÷"]=Op.BinaryOperation("÷"){$1/$0}
// knowOps["+"]=Op.BinaryOperation("+"){$0+$1}
// knowOps["-"]=Op.BinaryOperation("-"){$1-$0}
// knowOps["√"]=Op.UnaryOperation("√"){sqrt($0)}
} private func evaluate(ops:[Op])->(result:Double?,remainOps:[Op]){
if !ops.isEmpty {
var remainOps=ops;
let op=remainOps.removeLast()
switch op {
case Op.operand(let operand):
return(operand,remainOps)
case Op.UnaryOperation(_, let operation):
let operandEvalution=evaluate(remainOps)
if let operand=operandEvalution.result{
return(operation(operand),operandEvalution.remainOps)
}
case Op.BinaryOperation(_, let operation):
let operandEvlution1=evaluate(remainOps)
if let operand1=operandEvlution1.result {
let operandEvlution2=evaluate(operandEvlution1.remainOps)
if let operand2=operandEvlution2.result {
return (operation(operand1,operand2),operandEvlution2.remainOps)
}
} }
} return (nil,ops)
} func evaluate()->Double?{
let (result,remainder)=evaluate(opstack)
print("\(opstack)=\(result)with\(remainder)left over")
return result
} func pushOperand(operand:Double)->Double?{
opstack.append(Op.operand(operand))
return evaluate()
} func performOperation(symbol:String)->Double?{
if let operation=knowOps[symbol]{
opstack.append(operation)
} return evaluate() } }

controll修改为

import UIKit

class CalculViewController: UIViewController {

    @IBOutlet weak var display: UILabel!

    var userIsInTheMiddleOFTypingANumber:Bool=false
var brain=CalculatorBrain() @IBAction func appendDigit(sender: UIButton) {
let digit=sender.currentTitle!
if userIsInTheMiddleOFTypingANumber {
display.text=display.text!+digit
}else{
display.text=digit
userIsInTheMiddleOFTypingANumber=true
}
}
//var operandstack:Array<Double>=Array<Double>() @IBAction func operate(sender: UIButton) { if userIsInTheMiddleOFTypingANumber {
enter()
}
if let operation=sender.currentTitle{
if let result=brain.performOperation(operation) {
displayValue=result
}else{
displayValue=0
}
} } @IBAction func enter() {
userIsInTheMiddleOFTypingANumber=false
if let result=brain.pushOperand(displayValue){
displayValue=result
}else{
displayValue=0
} } var displayValue:Double{
get{
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set{
display.text="\(newValue)"
userIsInTheMiddleOFTypingANumber=false
}
} }

IOS之计算器实现的更多相关文章

  1. iOS小型计算器

    // //  ViewController.m //  计算器 //屏幕的宽和高 #define SCREEN_W self.view.frame.size.width #define SCREEN_ ...

  2. IOS OC 计算器算法(不考虑优先级)

    个人见解:为还在计算器算法方面迷惑的同学一个数据处理解决方案:定义一个可变数组array,一个可变字符串str,使字符通过[array addObject:str];方法添加到可变数组,每当触发运算符 ...

  3. iOS 收款计算器算法

    一个收款计算器算法,从之前高仿有赞Demo里面抽离的一个界面 demo 在这里 https://github.com/L-vinCent/calculView_function 显示计算记录 不能连续 ...

  4. iOS 减法计算器

    一: 在界面上拖入相应的控件 二: 给每个控件设置关联 //监听按钮的点击 - (IBAction)compute:(id)sender; //第一个文本输入框的值 @property (weak, ...

  5. c 语言简单计算器源码

    //  main.c //  计算器 //  Created by qianfeng on 14-7-15. //  Copyright (c) 2014年 ___FGY___. All rights ...

  6. 使用Olami SDK 语音控制一个支持HomeKit的智能家居的iOS程序

    前言 HomeKit是苹果发布的智能家居平台.通过HomeKit组件,用户可以通过iphone.iPad和ipod Touch来控制智能灯泡,风扇.空调等支持HomeKit的智能家居,尤其是可以通过S ...

  7. 【IOS开发笔记03-视图相关】简单计算器的实现

    UIView 经过前几天的快速学习,我们初步了解的IOS开发的一些知识,中间因为拉的太急,忽略了很多基础知识点,这些知识点单独拿出来学习太过枯燥,我们在今后的项目中再逐步补齐,今天我们来学习APP视图 ...

  8. 李洪强漫谈iOS开发[C语言-042]-简单计算器

    李洪强漫谈iOS开发[C语言-042]-简单计算器

  9. IOS实现小型计算器

    作为一名初学者,编辑一款能够在IOS操作系统上运行的计算器是一件很值得自豪的事情,网络上虽然后很多相关的文章和代码,功能也很强大但是我感觉相关的计算器比加复杂,晦涩难懂,所以我想通过这个小小的计算器, ...

随机推荐

  1. 如何把其他用户创建的表,导入到自己数据库是,所有者owner改变为自己创建的用户

     1. 导出用户 expdp user1/pass1 directory=dumpdir dumpfile=user1.dmp2. 导入用户 impdp user2/pass2 directory=d ...

  2. PYTHON seek()tell()语句

    print(f.tell()) # 显示当前位置 f.seek(0) #回到某一起点

  3. 剑指Offer 找出字符串中第一个只出现一次的字符

    题目描述 找出字符串中第一个只出现一次的字符 如果无此字符 请输出'.' 输入描述: 输入一串字符,由小写字母组成 输出描述: 输出一个字符 输入例子: asdfasdfo 输出例子: o 思路:数组 ...

  4. 剑指Offer 包含min函数的栈

    题目描述 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数.   思路: 这个题是想得到一个时间复杂度为O(1)的min函数,所以应用一个辅助栈,压的时候,如果A栈的压入比B栈压入 ...

  5. net-snmp的MIBs扩展(linux下)

    net-snmp的MIBs扩展 net-snmp的MIBs扩展 1 编译安装net-snmp 2 编写MIB文件 MIB文件描述 一个简单的示例 3 使自定义的MIB文件生效 4 实现agent代理程 ...

  6. QT国际化 一 (lupdate/linguits/lrelease)

    QT国际化(lupdate/linguits/lrelease) 本文由乌合之众瞎写http://www.cnblogs.com/oloroso/ qt国际化其实就是qt中字符串的字符集编码的设置.当 ...

  7. fzu2172 字符串dp

    F - 巡了南山我巡北山 Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit ...

  8. Service

      一.什么是Service Service在后台运行,不与用户进行交互.在默认情况下,Service运行在应用程序进程的主线程中,如果需要在Service中处理一些网络连接等耗时的操作,那么应该将这 ...

  9. Flatten 2D Vector

    Implement an iterator to flatten a 2d vector. For example, Given 2d vector = [ [1,2], [3], [4,5,6] ] ...

  10. ASP.NET MVC Dropdownlist

    本文介绍如何在网页里显示DropDownList. Step 1: 在Control里面添加方法 public ActionResult ShowDropDownList() { return Vie ...