Swift, get variable name from a string

后端 未结 1 824
失恋的感觉
失恋的感觉 2021-01-22 12:54

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 t

相关标签:
1条回答
  • 2021-01-22 13:03

    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);
    
    0 讨论(0)
提交回复
热议问题