Search code examples
matlabswifteval

Is there an equivalent "eval" function for swift, like there is in Matlab?


If not, how can I loop through IBOutlets (like temp1, temp2, temp3) and chance a property sequentially?

In matlab, I would concatenate a string and use eval.

for k = 1:3 
    eval(["temp",num2str(k)]);
end

I'm new to Swift, and want to do this with IBOutlets. Something like,

for(var k = 0, ++k, k==4) {
    eval(["self.temp",String(k),".backgroundcolor"]);
end

I know the eval function is in Matlab format, but I'm just expressing what I'd like to have done.


Solution

  • Swift is a static type language, so that it's impossible to implement something like "eval" in Matlab. You can reach same behaviour with this code:

    @IBOutlet var labels: [UILabel]!
    override func viewDidLoad() {
        super.viewDidLoad()
        for label in labels {
            label.backgroundColor = UIColor.redColor()
        }
    }
    

    Although probably it is possible to do some magic using the runtime, connecting all the components in the same outlet collection is the easiest way.