Last active
September 28, 2016 08:21
-
-
Save ken0nek/697bc1c0fce4273f71ea to your computer and use it in GitHub Desktop.
【Swift】文字列の計算式を処理する ref: http://qiita.com/ken0nek/items/a5e2be8b27d6b19d50dd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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