1

Is it possible to use a variable in a label name.

For example, my label is called button1text and I have a variable var x = 1.

Is there a way to do thisbutton(x)text?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Dylan Murphy
  • 167
  • 1
  • 13
  • You should check out [dictionaries](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html). – Tamás Sengel Jul 23 '17 at 18:30
  • Related: https://stackoverflow.com/questions/27321778/swift-converting-a-string-into-a-variable-name, https://stackoverflow.com/questions/31175358/for-loop-variable-name-use-swift, https://stackoverflow.com/questions/40585591/how-can-i-access-to-variable-name-and-change-string-to-it – Martin R Jul 23 '17 at 18:32
  • 2
    This question is a pure Swift question, there is no need for watchkit tag. – Mo Abdul-Hameed Jul 23 '17 at 18:32

3 Answers3

2

No. You can not have variable name in identifier.

Mohammad Sadiq
  • 5,070
  • 28
  • 29
2

Variable names are evaluated at compile time, so no, it's not possible (at runtime).

Alternatively use an array or assign tags to the labels and get the label with viewWithTag

vadian
  • 274,689
  • 30
  • 353
  • 361
0

You can use reflection with Mirror. The capabilities are very limited in the context you want but you can try something like:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var button2: UIButton!
    @IBOutlet weak var button3: UIButton!

    @IBAction func didTapGoButton(_ sender: Any) {
        let mirror = Mirror(reflecting: self)
        for child in mirror.children {
            if let v = child.label, v == "button2" {
                (child.value as! UIButton).titleLabel?.text = "changed"
            }
        }
    }
}
henrique
  • 1,072
  • 10
  • 17