-->

NSExpression\\NSNumber extension changed in Swift

2019-09-15 13:47发布

问题:

have some extension for NSNumber:

extension NSNumber {
    func factorialF() -> NSNumber {
        return tgamma(self.doubleValue + 1)
    }
}

then i use this extension in my calculation

var stringFunction: String = "FUNCTION(10,'factorialF')"
var expn: NSExpression = NSExpression(format: stringFunction)
var result = expn.expressionValueWithObject(with: nil, context: nil)

in Xcode 7.3.1 and Swift 2.2 all works but in Xcode 8 and Swift 3.0 i have some error in my extension NSNumber "No 'tgamma' candidates produce the expected contextual result type 'NSNumber'"

i was fixed this error but get new

extension NSNumber {
    func factorialF() -> Double {
        return tgamma(self.doubleValue + 1)
    }
}
var stringFunction: String = "FUNCTION(10,'factorialF')"
var expn: NSExpression = NSExpression(format: stringFunction)
var result = expn.expressionValue(with: nil, context: nil)

i got new error here

var result = expn.expressionValue(with: nil, context: nil)

error: Playground execution aborted: error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT). The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.

how correct fix the first error in extension NSNumber?

回答1:

fixed by

extension NSNumber {
    func factorialF() -> NSNumber {
        return tgamma(self.doubleValue + 1) as NSNumber
    }
}

and all works in Swift 3.0