Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将参数传递给Swift中NSExpression的自定义NSNumber函数?_Swift_Calculator_Nsnumber_Nsexpression - Fatal编程技术网

如何将参数传递给Swift中NSExpression的自定义NSNumber函数?

如何将参数传递给Swift中NSExpression的自定义NSNumber函数?,swift,calculator,nsnumber,nsexpression,Swift,Calculator,Nsnumber,Nsexpression,好了,伙计们,我正在努力解决这个问题:我已经设法让没有参数的自定义函数像这样工作: NSExpression(format: "function(1+1, 'myCustomFunction'").expressionValueWithObject(nil, context: nil) as! Double 但我不知道如何使用参数实现自定义函数,我已经尝试将以下字符串传递给NSExpression,但没有成功: "function(1+1, 'myCustomFunctionWithArgum

好了,伙计们,我正在努力解决这个问题:我已经设法让没有参数的自定义函数像这样工作:

NSExpression(format: "function(1+1, 'myCustomFunction'").expressionValueWithObject(nil, context: nil) as! Double
但我不知道如何使用参数实现自定义函数,我已经尝试将以下字符串传递给NSExpression,但没有成功:

"function(1+1, 'myCustomFunctionWithArgument(42)')" // 42 as the argument
其中,自定义函数如下所示:

public extension NSNumber {
    func myCustomFunctionWithArgument(x: Double) -> NSNumber
         //...
}
但是,我得到以下错误:

-[__NSCFNumber myCustomFunctionWithArgument(42)]: unrecognized selector sent to instance 0xb000000000000045
2016-03-14 18:23:00.755 MyApp[3517:263390] *** Terminating app due to uncaught exception 
我已经到处搜索过了,我只找到了Objective-C答案,就像本教程:


最后,他解释了如何在Objective-C上实现这一点,但没有用Swift。有什么办法吗?顺便说一句,这是我的计算器应用程序。

我得到了下面的代码,可以在Xcode 7.2.1中工作。您收到的错误与选择器有关,选择器需要记住的主要一点是,在本例中,函数名后面需要一个冒号(:),以表示函数只有一个参数

import Foundation

public extension NSNumber {
    func myCustomFunctionWithArgument(x: NSNumber) -> NSNumber {
        return self.doubleValue + x.doubleValue
    }
}

let stringExpression = "function(1+1, 'myCustomFunctionWithArgument:', 42)"
let expression = NSExpression(format: stringExpression)
let result = expression.expressionValueWithObject(nil, context: nil) as! NSNumber
print(result.doubleValue)