Linus G. Linus G. - 1 year ago 76
iOS Question

Array not appending images

I'm trying to append images to a 2Dimensional array. This is how I am doing it right now:

var imgArr1: [UIImage] = []
var imgArr2: [UIImage] = []

var allArrays = [imgArr1, imgArr2]

for array in 0 ..< allArrays.count {
for i in categories { //list of folder names used below
for img in fileNames("path/to/my/images/i") { //fileNames() returns all the files' names it finds in the folders
print(img) //this does print out the correct file names, for instance: "img_1.jpg"
allArrays[array].append(UIImage(named: img))
print(imgArr1) //this prints: "[]"`

We can assume that the loops and custom functions are working. (Note my comments in the code: the image names are correctly printed out.)

I already tried other methods to append the new image to the array, like
insert at index
and using

Any ideas?

Thanks in advance!

Answer Source
for var array in allArrays

makes a mutable copy of the array. Appending to it won't mutate the original array, because arrays are value types. You'll have to add the images to imgArr1 (or imgArr2, or both) directly in order for this to work.

Edit: As an example on how to do this, you can loop through the indices of the outer array and modify the inner arrays using subscripts:

var all: [[Int]] = [[], [], []]

for arrayIndex in 0 ..< all.count {
    for number in 0 ..< 10 {

print(all.first!.count) // 10
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download