jobonki
jobonki

Reputation: 23

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.

Upvotes: 2

Views: 4262

Answers (2)

Giordano Scalzo
Giordano Scalzo

Reputation: 6342

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.

Upvotes: 3

Related Questions