use*_*280 7 arrays math ios swift
在Swift中有可能有一组算术运算符吗?就像是:
var operatorArray = ['+', '-', '*', '/'] // or =[+, -, *, /] ?
Run Code Online (Sandbox Code Playgroud)
我只想随机生成数字,然后从上面的数组中随机选择算术运算符并执行等式.例如,
var firstNum = Int(arc4random_uniform(120))
var secondNum = Int(arc4random_uniform(120))
var equation = firstNum + operatorArray[Int(arc4random_uniform(3))] + secondNum //
Run Code Online (Sandbox Code Playgroud)
上面的'等式'会起作用吗?
谢谢.
Air*_*ity 11
它会 - 但你需要使用不同的运算符.
单一操作员:
// declare a variable that holds a function
let op: (Int,Int)->Int = (+)
// run the function on two arguments
op(10,10)
Run Code Online (Sandbox Code Playgroud)
使用数组,您可以使用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, 0, 100, 1]
Run Code Online (Sandbox Code Playgroud)