本文利用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. 服务器&域名那些事儿

    购买的阿里云的服务器(ECS)和域名 请移步: 服务器&域名那些事儿 服务器&域名那些事儿2 github 博客

  2. MAC地址,使用java获取IP地址和MAC地址。

    MAC地址,通常在http连接的项目中,来区分唯一客户端. MAC:六组十六进制字符组成. 如:E0-3F-49-AB-DB-EB IP:四组八位的二进制字符组成. 如:10.6.62.244 /** ...

  3. Linux 利器- Python 脚本编程入门(一)

    导读 众所周知,系统管理员需要精通一门脚本语言,而且招聘机构列出的职位需求上也会这么写.大多数人会认为 Bash (或者其他的 shell 语言)用起来很方便,但一些强大的语言(比如 Python)会 ...

  4. delay() .split()

    delay(500) 延时多少秒后执行,结合animate()使用 delay(500).animate({},时间) .split() stringObject.split(separator,ho ...

  5. Apache 无法启动

    本人是做前端开发的,对后台程序不太熟悉,也就以前学过一点.net.但现在都忘记的差不多了.最近在公司,经理给了我一个管理工具dedecms,我刚开始看的时候完全不懂这是什么东西,之前都没听说过(本人见 ...

  6. BZOJ 2448: 挖油

    Description [0,x]中全是1,其余全是0,每个点有一个权值,求最坏情况下得到x的最小权值. Sol DP+单调队列. 首先就是一个 \(O(n^3)\) 的DP. \(f[i][j]\) ...

  7. 2. Android系统启动流程

    1.启动加载完内核 2.执行init进程   ----> 设备初始化工作       a1. 读取inic.rc       a2. 启动Zygote进程 ----> 该进程是所有进程的孵 ...

  8. ASP.NET 页生命周期概述

    ASP.NET 页生命周期概述 Visual Studio 2005    ASP.NET 页运行时,此页将经历一个生命周期,在生命周期中将执行一系列处理步骤.这些步骤包括初始化.实例化控件.还原和维 ...

  9. hadoop初识

    搞什么东西之前,第一步是要知道What(是什么),然后是Why(为什么),最后才是How(怎么做).但很多开发的朋友在做了多年项目以后,都习惯是先How,然后What,最后才是Why,这样只会让自己变 ...

  10. NGUI 图片变灰

    效果图 1.先准备好一个变灰shader.代码如下 Shader "Custom/Gray" { Properties { _MainTex ("Base (RGB), ...