Skip to content

Instantly share code, notes, and snippets.

@heitortsergent
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heitortsergent/4c74855bf5a7c35f4d12 to your computer and use it in GitHub Desktop.
Save heitortsergent/4c74855bf5a7c35f4d12 to your computer and use it in GitHub Desktop.
Swift Type Inference
var operandStack = Array<Double>()
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter()
}
switch operation {
case “x”:
if operandStack.count >= 2 {
displayValue = operandStack.removeLast() * operandStack.removeLast()
enter()
}
case “/”:
if operandStack.count >= 2 {
displayValue = operandStack.removeLast() / operandStack.removeLast()
enter()
}
case “+”:
if operandStack.count >= 2 {
displayValue = operandStack.removeLast() + operandStack.removeLast()
enter()
}
case “-”:
if operandStack.count >= 2 {
displayValue = operandStack.removeLast() - operandStack.removeLast()
enter()
}
default: break
}
}
// We can create a function to perform each operation
// so we can get rid of the repeated if's and enter()
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter()
}
switch operation {
case “x”: performOperation(multiply)
case “/”: performOperation(divide)
case “+”: performOperation(add)
case “-”: performOperation(subtract)
default: break
}
}
func performOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast, operandStack.removeLast())
enter()
}
}
func multiply(op1: Double, op2: Double) -> Double {
return op1 * op2
}
// The above is not that much better, because we still have the
// multiply, divide, add and subtract methods.
// We can avoid that by using closures
// (I'll just focus on one operation to avoid copy+pasting)
case “x”: performOperation({ (op1: Double, op2: Double) -> Double in
return op1 * op2
// The performOperation method expects two Doubles, and returns
// a Double, so we can get rid of the variable types declaration
case “x”: performOperation({ (op1, op2) in return op1 * op2 })
// We can get rid of the return as well since our closure
// only contains a single expression
case “x”: performOperation({ (op1, op2) in op1 * op2 })
// We can also get rid of the closure parameter names and in
// keyword, and use shorthand argument names $0 and $1
case “x”: performOperation({ $0 * $1 })
// Since the function is the last parameter the
// performOperation method takes, we can move it
// outside of the parenthesis
case “x”: performOperation() { $0 * $1 }
// And, finally, since we don't have any other
// parameters, we can just get rid of the parenthesis.
// This is the final result. :)
case “x”: performOperation { $0 * $1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment