clearwater223
clearwater223

Reputation: 17

Looping through array of strings (iterating images)

I'm fairly new to Swift and having some trouble iterating through a list of images to animate them. I have all of them named, for instance "aquarium-x", with x being a number from 1-29, depending on how many images I have for the specific animation. This is the code that I have for that part

func checkAnimationImages() -> [AnyObject] {
    var i = 0
    var catGifArray = [UIImage]()
    var image = UIImage(named: "-\(i)")
    while (image != nil){
        catGifArray.append(image!)
        ++i
        image = UIImage(named: "-\(i)")
    }
   return catGifArray.map {
        return $0.CGImage as! AnyObject
    }
}

My problem is I can't figure out how to also incorporate an array of strings into the UIImage so I don't need to type all the names out.

var catGifName:[String] = [
        "3d",
        "piano1",
        "aquarium",
        "bag",
        "bitey",
        "black",
        "blackcat"]

I tried to put the name of the array in the "-/(i)" portion but that gives back an error.

Upvotes: 1

Views: 222

Answers (2)

Kyle Redfearn
Kyle Redfearn

Reputation: 2281

It looks like what you need is a nested for loop:

var images = [UIImage]()
let catGifName = ["cat","piano","aquarium","bag"]
for name in catGifName {
    for i in 1...29 {
        if let image = UIImage(named:"\(name)-\(i)") {
            images.append(image)
        }
    }
}

Upvotes: 1

creeperspeak
creeperspeak

Reputation: 5521

I think what you probably need is to pass in your list of filenames, and add the images to the array in a similar manner you were starting. It'd be something like this:

func checkAnimationImages(fileNames: [String]) -> [AnyObject] {
for name in fileNames {
    var i = 0
    var catGifArray = [UIImage]()
    var image = UIImage(named: "\(name)-\(i)")
    while (image != nil){
        catGifArray.append(image!)
        ++i
        image = UIImage(named: "\(name)-\(i)")
    }
}
return catGifArray.map {
    return $0.CGImage as! AnyObject
}
}

Of course the UIImage(named:...) only works if the image is in the main bundle, but I assume that's how you've set yourself up.

Anyway, you'd call it like...

self.checkAnimationImages(self.catGifNames)

Upvotes: 0

Related Questions