koz koz - 1 year ago 70
Swift Question

How to perform the same method on outlets that have similar names instead of writing out very similar lines 10s of times?

I have these outlets...

@IBOutlet weak var pill1: UIImageView!
@IBOutlet weak var pill2: UIImageView!
@IBOutlet weak var pill3: UIImageView!
@IBOutlet weak var pill4: UIImageView!
@IBOutlet weak var pill5: UIImageView!
@IBOutlet weak var pill6: UIImageView!
@IBOutlet weak var pill7: UIImageView!
@IBOutlet weak var pill8: UIImageView!
@IBOutlet weak var pill9: UIImageView!
@IBOutlet weak var pill10: UIImageView!

I need to hide all of them in the 'viewDidLoad' function. For example...

self.pill1.isHidden = true
self.pill2.isHidden = true
self.pill3.isHidden = true
etc....all the way to...
self.pill10.isHidden = true

But instead of writing repetitive lines 10s of times that are very similar, how do I use a 'for loop', or whatever is needed, to make it more cleaner.

For example,

for index in 1...10 {

pill(insert index here somehow).isHidden = true


I tried a few different ways, but I was getting errors with string types etc. I am new to this all. Any help appreciated. thank you

Answer Source

You can put the views into an array like this:

for pill in [pill1, pill2, pill3, pill4, pill5, pill6, pill7, pill8, pill9, pill10] {
    pill.isHidden = true

You could consider using an @IBOutlet collection. In that case, all of your outlets would be wired to the same collection (array) variable:

@IBOutlet var pills: [UIImageView]!

for pill in pills {
    pill.isHidden = true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download