Mathematical Parser in Swift [closed]

南笙酒味 提交于 2019-12-13 04:59:57

问题


I am wondering if there are any nice Mathematical Parsers in Swift. That is, it can take a string and solve it. I need it to have factorials, exponents, square roots, and all the basic arithmetic operators. I want it to be built into Swift, not 3rd party(like DDMathParser and GCMathParser)It would be nice if you could a couple of them.


回答1:


There is no mathematical expression parser “built into Swift” in the way you mean.

There is an expression evaluator included with the Foundation framework, which is part of iOS and Mac OS X and is accessible from both Objective-C and Swift. It's called NSExpression.

Example:

let expression = NSExpression(format: "2+3*4")
print(expression.expressionValueWithObject(nil, context: nil))
// prints "14"

It doesn't include a factorial function, but this article describes how to add your own functions, and uses factorial as an example. You'll have to translate the example from Objective-C to Swift yourself.

The main problem with using NSExpression is that, if the expression string has any errors, it simply crashes.

:; 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) 

So if you want to take strings provided by the user and parse them as mathematical expressions, you must either write your own parser, or use a third-party parser like DDMathParser.



来源:https://stackoverflow.com/questions/31168751/mathematical-parser-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!