Skip to content

Instantly share code, notes, and snippets.

@ken0nek
Last active September 28, 2016 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ken0nek/697bc1c0fce4273f71ea to your computer and use it in GitHub Desktop.
Save ken0nek/697bc1c0fce4273f71ea to your computer and use it in GitHub Desktop.
【Swift】文字列の計算式を処理する ref: http://qiita.com/ken0nek/items/a5e2be8b27d6b19d50dd
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
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.expressionValueWithObject(nil, context: nil) as! Double
print(output)
// 5.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment