我想知道Swift中是否有任何好的数学解析器。也就是说,它可以采用字符串并解决它。我需要它有阶乘,指数,平方根和所有基本算术运算符。我希望它可以内置到Swift中,而不是第三方(如DDMathParser和GCMathParser)。如果你可以使用它们,那就太好了。
答案 0 :(得分:5)
没有数学表达式解析器以“你的意思”内置“Swift”。
Foundation框架中包含一个表达式评估程序,它是iOS和Mac OS X的一部分,可以从Objective-C和Swift访问。它被称为NSExpression
。
示例:
let expression = NSExpression(format: "2+3*4")
print(expression.expressionValueWithObject(nil, context: nil))
// prints "14"
它不包含阶乘函数,但this article描述了如何添加自己的函数,并使用阶乘作为示例。您必须自己将示例从Objective-C转换为Swift。
使用NSExpression
的主要问题是,如果表达式字符串有任何错误,它只会崩溃。
:; xcrun swift
Welcome to Apple Swift version 4.0.3 (swiftlang-900.0.74.1 clang-900.0.39.2). Type :help for assistance.
1> import Foundation
2> let ex = NSExpression(format: "1+", argumentArray: [])
Process 78868 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = internal ObjC exception breakpoint(-5).
frame #0: 0x0000000100000e90 repl_swift`repl_swift.repl_main() -> Swift.Int
repl_swift`repl_swift.repl_main() -> Swift.Int:
-> 0x100000e90 <+0>: pushq %rbp
0x100000e91 <+1>: movq %rsp, %rbp
0x100000e94 <+4>: xorl %eax, %eax
0x100000e96 <+6>: popq %rbp
Target 0: (repl_swift) stopped.
ex: NSExpression = <extracting data from value failed>
Execution stopped at breakpoint. Enter LLDB commands to investigate (type help for assistance.)
(lldb)
因此,如果您想获取用户提供的字符串并将其解析为数学表达式,则必须编写自己的解析器,或者使用第三方解析器,如DDMathParser
。