Swift中的数学解析器 [英] Mathematical Parser in Swift

查看:143
本文介绍了Swift中的数学解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Swift中是否有任何不错的数学解析器.也就是说,它可以采用一个字符串并解决它.我需要它具有阶乘,指数,平方根以及所有基本的算术运算符.我希望将其内置到Swift中,而不是第3方中(例如DDMathParser和GCMathParser),如果您可以选择其中的几个,那就太好了.

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.

推荐答案

没有按照您的意思内置到Swift中"的数学表达式解析器.

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

Foundation框架包含一个表达式 evaluator ,它是iOS和Mac OS X的一部分,可从Objective-C和Swift进行访问.它叫做NSExpression.

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.

示例:

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

它不包含阶乘函数,但是本文介绍了如何添加自己的函数,并以阶乘为例.您必须自己将示例从Objective-C转换为Swift.

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.

使用NSExpression的主要问题是,如果表达式字符串有任何错误,它只会崩溃.

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) 

因此,如果要使用用户提供的字符串并将其解析为数学表达式,则必须编写自己的解析器,或者使用第三方解析器(例如DDMathParser).

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.

这篇关于Swift中的数学解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆