使用 swift 类在 MathParser swift 框架和 Objective-c 项目之间架起桥梁,@objc public func evaluateString(string: String, substitutions:Substitutions = [:]) throws -> NSNumber
使用 Swift 3 编译没有问题,但 Swift 4 不会接受它。
尝试声明 as
@objc public func evaluateString(string: String, substitutions: Dictionary<String, Any> = [:]) throws -> NSNumber
,它编译但是运行时错误指示 EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) 在尝试向下转换时substitutions
。
MathParser 可以在https://github.com/davedelong/DDMathParser/tree/master/MathParser找到。欣赏这里的任何方向,因为 swift 有点笨拙。
import Foundation
import MathParser
@objc public enum AngleMode : Int {
case Radians
case Degrees
}
@objc public class DDMathParser : NSObject
{
@objc public var angleMeasurementMode = AngleMode.Radians
@objc public var Error : NSError?
// @objc public func evaluateString(string: String, substitutions: Dictionary<String, Any> = [:]) throws -> NSNumber
@objc public func evaluateString(string: String, substitutions:Substitutions = [:]) throws -> NSNumber
{
do {
let evaluator = Evaluator()
let expression = try Expression(string: string as String)
// let bridgedSubstitutions = substitutions as? Substitutions
let value = try evaluator.evaluate(expression, substitutions: substitutions!)
return NSNumber .init(value: value);
} catch let error as MathParserError {
…………
public protocol Substitution {
func substitutionValue(using evaluator: Evaluator, substitutions: Substitutions) throws -> Double
func substitutionValue(using evaluator: Evaluator) throws -> Double
func simplified(using evaluator: Evaluator, substitutions: Substitutions) -> Substitution
func simplified(using evaluator: Evaluator) -> Substitution
}
public extension Substitution {
func substitutionValue(using evaluator: Evaluator) throws -> Double {
return try substitutionValue(using: evaluator, substitutions: [:])
}
func simplified(using evaluator: Evaluator) -> Substitution {
return simplified(using: evaluator, substitutions: [:])
}
}
public typealias Substitutions = Dictionary<String, Substitution>