目录

SwiftCalc

A Swift package for parsing and evaluating mathematical expressions.

The parser supports the basic math operators, variables and functions (defined in Swift). Under the hood it uses the wonder Owl Parser Generator https://github.com/ianh/owl.

Basic support for syntax coloring is provided in an extension of AttributedString.

Usage

There are three main types in this package: Compiler which compiles an expression string into CompiledProgram and then Executor which evaluates the CompiledProgram. The Executor can be reused for multiple expressions.

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()
}

Demo Screenshot

Alt text

邀请码
    Gitlink(确实开源)
  • 加入我们
  • 官网邮箱:gitlink@ccf.org.cn
  • QQ群
  • QQ群
  • 公众号
  • 公众号

版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9 京公网安备 11010802032778号