SwiftCalc

一个用于解析和计算数学表达式的 Swift 包。

该解析器支持基本的数学运算符、变量和函数(在 Swift 中定义)。其底层使用了优秀的 Owl Parser Generator https://github.com/ianh/owl

AttributedString 的扩展中提供了对语法着色的基本支持。

使用方法

这个包中有三个主要的类型:Compiler,它将表达式字符串编译成 CompiledProgram;然后是 Executor,它计算 CompiledProgram 的值。 Executor 可以被复用于多个表达式。

import SwiftCalc

let variables: [String: Value] = [
    "pi": .number(.pi),
    "sin": .function(Math.sin),
]
let program = try Compiler().compile("sin(1) * 10 * pi")
program.dump()
let executor = Executor(variables: variables)
let result = try executor.execute(program)
guard case let .number(resultValue) = result else {
    fatalError()
}

演示截图

Alt text