问题描述
我有一个问题。我知道这可以在Ruby中完成,不确定Swift,但从未做过类似的事情。
我正在研究的是一个与此类似的程序:如果用户在TextViewa + b中写入,我的代码应该详细说明变量a和b之间的总和值。
我的意思是,如何从字符串中获取变量名?它有可能吗?
I have a question. I know that this can be done in Ruby, not sure about Swift, but never did anything similar.What I'm working on is a program that works similar to this: if the user writes in a TextView "a + b", my code should elaborate the value of the sum between the variable "a" and "b".What I mean is, how can I get variable names from a string? Is it possible at all?
如果不是,我会使用一个开关(变量名有限),但我需要连接一个变量到用户写的那个。在这个例子中,如果用户写a + b,我的sum函数就像sum(par1,par2),那么,我怎样才能使变量par1指向a和par2指向b?我可以用指针做到这一点吗?还有其他方法吗?
If it's not, I'd use a switch (variable names are limited), but I'd need to "connect" a variable to the one written by the user. In the example, if the user writes "a + b", my sum function is something like "sum(par1,par2)", so, how can I make variable "par1" point to "a" and "par2" point to "b"? I can do that with pointers right? Is there any other way?
我不确定我是否已经清楚,但很难解释
I'm not sure I've been clear, but it's quite hard to explain
推荐答案
检查一下。您可以使用 NSExpression
和 KVC
。
Check this out. You can do with NSExpression
and KVC
.
class myclass:NSObject {
var a = 10;
var b = 20;
override init() {
super.init();
}
}
var obj = myclass();
// Expression from user
var expr:NSString = "a+b" ;
//Operators..
let opSet = NSMutableCharacterSet()
opSet.addCharactersInString("+-*/");
let components:NSArray = expr.componentsSeparatedByCharactersInSet(opSet)
let uniqueChars:NSSet = NSSet(array: components)
for variable in uniqueChars
{
expr = expr.stringByReplacingOccurrencesOfString ( variable as String,
withString : NSString(format: "%d", obj.valueForKey(variable as String) as Int),
options : NSStringCompareOptions.LiteralSearch,
range : NSMakeRange(0,expr.length) );
}
var result: AnyObject = NSExpression(format: expr).expressionValueWithObject(nil, context: nil)
print (result);
这篇关于Swift,从字符串中获取变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!