Xpre 8.3.1•Swift 3.1
extension String { var expression: NSexpression { return NSexpression(format: self) }}let a = 5let b = 2let intDictionary = ["a": a,"b": b]var formula = "a * b"if let timesResult = formula.expression.expressionValue(with: intDictionary, context: nil) as? Int { print(timesResult) // 10}formula = "(a + b) / 2"if let intAvgResult = formula.expression.expressionValue(with: intDictionary, context: nil) as? Int { print(intAvgResult) // 3}let x = 5.0let y = 2.0let z = 3.0let doubleDictionary = ["x": x, "y": y, "z": z]formula = "(x + y + z) / 3"if let doubleAvgResult = formula.expression.expressionValue(with: doubleDictionary, context: nil) as? Double { print(doubleAvgResult)}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)