I am following a stanford online lecture series in which the professor demoes a calculator app. I am posting the viewcontroller.swift file code below and a screen shot of my current main.storyboard.
What I need to know, is how am I supposed to define multiple definitions for the same function? as you can see, I need to define a function operation which may have one or two variables as inout. I looked through the swift reference on why I am getting this error here. However, it does not mention anything close to what he does. I believe this is due to some changes in swift version, although I'm not sure.
I went through the reference and found the declaration in the format func funcName ( Double... ) to pass variable number of parameters, but I don't exactly know how I am to use that kind of instantiation here.
ViewController.swift:
import UIKit
class ViewController: UIViewController {
@IBOutlet var display: UILabel!
var userIsInTheMiddleOfTyping = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func numberPressed(sender: UIButton) {
// We need to get the value from the current label
// And then we need to update it with appending the pressed digit at the ending.
let digit = sender.currentTitle!
if ( userIsInTheMiddleOfTyping ){
display.text = display.text! + digit
} else{
display.text = digit
userIsInTheMiddleOfTyping = true
}
}
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTyping{
enter()
}
switch operation {
case "*": performOperation { $0 * $1 }
case "/": performOperation { $1 / $0 }
case "+": performOperation { $0 + $1 }
case "-": performOperation { $1 - $0 }
case "sqrt": performOperation( sqrt($0))
default: break
}
}
func performOperation( operation: (Double,Double)->Double){
if operandStack.count >= 2{
displayValue = operation(operandStack.removeLast() , operandStack.removeLast())
enter()
}
}
func performOperation( operation: Double -> Double ){
if operandStack.count >= 1{
displayValue = operation(operandStack.removeLast())
enter()
}
}
var operandStack = Array<Double>()
@IBAction func enter() {
userIsInTheMiddleOfTyping = false
operandStack.append(displayValue)
print(operandStack)
}
var displayValue: Double{
get{
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set{
display.text = "\(newValue)"
userIsInTheMiddleOfTyping = false
}
}
}