map array uiimage in swift

To map an array of UIImages, you can use the map method with a closure. Here's an example:

main.swift
let imageNames = ["image1", "image2", "image3"]
let images = imageNames.map { name in
    UIImage(named: name)!
}
114 chars
5 lines

In this example, we have an array of image names. We use the map method to create a new array called images where each element is a UIImage initialized with its corresponding name from the imageNames array.

Note that the closure passed to map takes an input parameter name of type String and returns a value of type UIImage. It force-unwraps the result of the UIImage(named:) initializer because we know that the image names specified in imageNames exist in our app's asset catalog. If you're not certain whether an image exists, you should use optional binding (i.e. if let) to safely unwrap the result of UIImage(named:).

related categories

gistlibby LogSnag