Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Arithmetic Operators in Swift

Is it possible to have an array of arithmetic operators in Swift? Something like:

var operatorArray = ['+', '-', '*', '/'] // or =[+, -, *, /] ?

I just want to randomly generate numbers and then randomly pick an arithmetic operator from the array above and perform the equation. For example,

var firstNum  = Int(arc4random_uniform(120))
var secondNum = Int(arc4random_uniform(120))
var equation = firstNum + operatorArray[Int(arc4random_uniform(3))] + secondNum // 

Will the above 'equation' work?

Thank you.

like image 647
user3345280 Avatar asked Feb 11 '15 00:02

user3345280


2 Answers

It will - but you need to use the operators a little differently.

Single operator:

// declare a variable that holds a function 
let op: (Int,Int)->Int = (+)
// run the function on two arguments
op(10,10)

And with an array, you could use map to apply each one:

// operatorArray is an array of functions that take two ints and return an int
let operatorArray: [(Int,Int)->Int] = [(+), (-), (*), (/)]

// apply each operator to two numbers
let result = map(operatorArray) { op in op(10,10) }

// result is [20, 0, 100, 1]
like image 155
Airspeed Velocity Avatar answered Sep 28 '22 09:09

Airspeed Velocity


You can use NSExpression class for doing the same.

var operatorArray = ["+", "-", "*", "/"]
var firstNum      = Int(arc4random_uniform(120))
var secondNum     = Int(arc4random_uniform(120))
var equation      = "\(firstNum) \(operatorArray[Int(arc4random_uniform(3))]) \(secondNum)"

var exp = NSExpression(format: equation, argumentArray: [])
println(exp.expressionValueWithObject(nil, context: nil))
like image 28
Midhun MP Avatar answered Sep 28 '22 09:09

Midhun MP