0

I have number of images and they are named as image0, image1, image2..., image(x).

My question is how can I access their name because I want to put all of them in array like:

@IBOutlet weak var image0: UIImageView!
@IBOutlet weak var image1: UIImageView!
@IBOutlet weak var image2: UIImageView!
@IBOutlet weak var image3: UIImageView!
@IBOutlet weak var image4: UIImageView!
@IBOutlet weak var image5: UIImageView!
...
@IBOutlet weak var image15: UIImageView!
    var counter: Int = 0
    var items :[[UIImageView]] = []
    for i in 0..<4{
        for j in 0..<4{
            items[i][j]=image(counter) //this line should be something that image0,1..x assign to the array
            counter += 1
        }
    }
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253

2 Answers2

0

You can do this through the following code.

Swift 3

var items : [[UIImageView]] = []
let myMirror = Mirror(reflecting: self)
for i in 0..<4 {
    items.insert([UIImageView](), at: i)
    for j in 0..<4 {
        let propertyName = "image\(i*4 + j)"
        items[i].insert(myMirror.descendant(propertyName) as! UIImageView, at: j)
    }
}

However, this is not code that is used by devs, Look into using a UICollectionView

Community
  • 1
  • 1
Carien van Zyl
  • 2,853
  • 22
  • 30
0

I see what you are trying to do. Sadly variable names are evaluated at compile time, so that's not possible. The best thing you can do is to manually create the array.

[[image0, image1, image2], [image3, image2, image3], ...]
ntoonio
  • 3,024
  • 4
  • 24
  • 28