Get an outlet variable by name

Viewed 1385

Looking for a way to access an outlet programmatically in swift:

@IBOutlet var label1: UILabel?
var outletName = "label1"
view[outletName].text = "hello, world!"

Is the only way to do this to create my own custom mapping, like so?

@IBOutlet var label1: UILabel?
let outlets = ["label1": label1]
let outletName = "label1"
outlets[outletName].text = "hello, world!"

EDIT: Seems my original question was poorly worded, lets try again:
I'm looking to access a variable through some string identifier. In my original question I was trying to ask if a variable can be accessed by the name of the variable itself somehow. IE accessing variable label1 with a string of the variable's name "label1".

3 Answers

Swift 5 version:

if let aLabel = value(forKey: "label1") as? UILabel {
    aLabel.text = "Hello World"
}
Related