2017/10/04 - Swift4で動作確認。
NSExpression
NSExpressionというものを使って、"5+8/4-2"のような文字列を計算したいと思います。
コード
let numList = [5, 8, 4, 2].map { String(Double($0)) } // 割り算を正確に行うためにDouble型への変換をはさむ
print(numList)
// ["5.0", "8.0", "4.0", "2.0"]
let opeList = ["+", "/", "-"]
let zipped = zip(numList, opeList + [""])
let equation = zipped.reduce("") { $0 + $1.0 + $1.1 }
print(equation)
// "5.0+8.0/4.0-2.0"
let expression = NSExpression(format: equation)
let output = expression.expressionValue(with: nil, context: nil) as! Double
print(output)
// 5.0