ios – Swift中的算术运算符数组

Swift中有可能有一组算术运算符吗?就像是:
var operatorArray = ['+','-','*','/'] // or =[+,-,*,/] ?

我只想随机生成数字,然后从上面的数组中随机选择算术运算符并执行等式.例如,

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

上面的’等式’会起作用吗?

谢谢.

解决方法

它会 – 但你需要使用不同的运算符.

单一运算符:

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

使用数组,您可以使用map来应用每个数组:

// 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,100,1]

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...