IOS之计算器实现
本文利用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之计算器实现的更多相关文章
- iOS小型计算器
// // ViewController.m // 计算器 //屏幕的宽和高 #define SCREEN_W self.view.frame.size.width #define SCREEN_ ...
- IOS OC 计算器算法(不考虑优先级)
个人见解:为还在计算器算法方面迷惑的同学一个数据处理解决方案:定义一个可变数组array,一个可变字符串str,使字符通过[array addObject:str];方法添加到可变数组,每当触发运算符 ...
- iOS 收款计算器算法
一个收款计算器算法,从之前高仿有赞Demo里面抽离的一个界面 demo 在这里 https://github.com/L-vinCent/calculView_function 显示计算记录 不能连续 ...
- iOS 减法计算器
一: 在界面上拖入相应的控件 二: 给每个控件设置关联 //监听按钮的点击 - (IBAction)compute:(id)sender; //第一个文本输入框的值 @property (weak, ...
- c 语言简单计算器源码
// main.c // 计算器 // Created by qianfeng on 14-7-15. // Copyright (c) 2014年 ___FGY___. All rights ...
- 使用Olami SDK 语音控制一个支持HomeKit的智能家居的iOS程序
前言 HomeKit是苹果发布的智能家居平台.通过HomeKit组件,用户可以通过iphone.iPad和ipod Touch来控制智能灯泡,风扇.空调等支持HomeKit的智能家居,尤其是可以通过S ...
- 【IOS开发笔记03-视图相关】简单计算器的实现
UIView 经过前几天的快速学习,我们初步了解的IOS开发的一些知识,中间因为拉的太急,忽略了很多基础知识点,这些知识点单独拿出来学习太过枯燥,我们在今后的项目中再逐步补齐,今天我们来学习APP视图 ...
- 李洪强漫谈iOS开发[C语言-042]-简单计算器
李洪强漫谈iOS开发[C语言-042]-简单计算器
- IOS实现小型计算器
作为一名初学者,编辑一款能够在IOS操作系统上运行的计算器是一件很值得自豪的事情,网络上虽然后很多相关的文章和代码,功能也很强大但是我感觉相关的计算器比加复杂,晦涩难懂,所以我想通过这个小小的计算器, ...
随机推荐
- Error 0x800704cf
重装了系统,改过网络配置,结果共享和打印机连不上,显示Error 0x800704cf 在本地连接的属性里将"Client for Microsoft Networks"勾选上就可 ...
- UNITY3d在移动设备上的一些优化实战(一)-概述
转自:UNITY3d在移动设备上的一些优化实战(一)-概述 http://blog.csdn.net/leonwei/article/details/39233921 项目进入了中期之后,就需要对程序 ...
- uMlet建模工具
下载:http://www.umlet.com/ 无意中发现的一款建模工具,能快速搭建数据库模型,前置安装条件是java环境. 这是我建的user模型表,2个字段name和age,2个方法getAge ...
- SSH-Struts第一弹:ActionSupport类
Action继承了com.opensymphony.xwork2.ActionSupport. package com.candy.login; import com.opensymphony.xwo ...
- CH Round #55 - Streaming #6 (NOIP模拟赛day2)解题报告
T1九九归一 描述 萌蛋在练习模n意义下的乘法时发现,总有一些数,在自乘若干次以后,会变成1.例如n=7,那么5×5 mod 7=4,4×5 mod 7=6,6×5 mod 7=2,2×5 mod 7 ...
- iframe框架中用js改变父级Url
<script type="text/javascript"> var path = window.location.href;//当前也面的跳转 ...
- win7桌面背景地址
C:\Users\你的用户名\AppData\Local\Microsoft\Windows\Themes\Alaskan L\DesktopBackground
- CRC在线计算器
On-line CRC calculation and free library https://www.lammertbies.nl/comm/info/crc-calculation.html
- rsa加密解密
2016年3月17日 17:21:08 星期四 现在越来越懒了.... 参考: http://www.xuebuyuan.com/1399981.html 左边是加密流程, 右边是解密流程 呃...有 ...
- Maven 3.3.3 Win10环境下的使用实例(下)
这一篇文章将介绍如何在 Eclipse 中使用 Maven. 我们以 Eclipse Java EE 版本为例,首先要对 IDE 进行一些设置: JDK 环境 Maven 的本地安装路径 Maven ...