Skip to content

Instantly share code, notes, and snippets.

@kurtisdunn
Created June 11, 2015 07:41
Show Gist options
  • Save kurtisdunn/db901d3dadb405bd83fc to your computer and use it in GitHub Desktop.
Save kurtisdunn/db901d3dadb405bd83fc to your computer and use it in GitHub Desktop.
Calculator controller before MVC. - Swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingANumber: Bool = false
@IBAction func appendDigit(sender: UIButton) {
// Get current value of button pressed
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
display.text = display.text! + digit
}
else{
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
// plus minus x divide function.
@IBAction func operate(sender: UIButton) {
// Set the symbol pressed
let operation = sender.currentTitle!
//when symbol pressed check for case
if userIsInTheMiddleOfTypingANumber{
enter()
}
switch operation{
case "×": performOperation() { $0 * $1 }
case "÷": performOperation() { $1 / $0 }
case "+": performOperation() { $0 + $1 }
case "-": performOperation() { $1 - $0 }
case "√": performOperation() { sqrt($0) }
default : break
}
}
private func performOperation(operation: (Double, Double) -> Double){
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
private func performOperation(operation: (Double) -> Double){
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
enter()
}
}
//var is array = init a empty array. this is an array of doubles.
var operandStack = Array<Double>()
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
operandStack.append(displayValue)
println("operandStack = \(operandStack)")
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set{
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment