LoginSignup
5
6

More than 5 years have passed since last update.

【Swift】文字列の計算式を処理する

Last updated at Posted at 2015-08-19

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

参考

【Swift】2つの配列を交互につなぎ合わせる
【Swift】Int型の数字から[Int]型の配列を生成する

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6