How to add new instance of an object to an array of objects XCode

Viewed 55

I have an array called imageCollection which contains all the photos on the device. I want to display these in a more robust way, for example as a photos collage on screen. In order to do this I have created a struct ImageObject which has additional properties like the x and y coordinates. I want to store a group of ImageObjects in an array imageObjectGroup, where each instance contains one image from my camera roll. Ultimately creating an instance of imageObject for each photo in my camera roll. I need help constructing this for loop that creates a new imageObjects instance. It can be found at the bottom of the function that populates imageCollection (array with all images from camera roll)

Code:

// Array containing all the images from camera roll
var imageCollection = [PHAsset]()

// Populating array with all images for loop is also here that adds each photo as a imageObjects instance
func getImages() {
    let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil)
    assets.enumerateObjects({ (object, count, stop) in
       // self.cameraAssets.add(object)
        imageCollection.append(object)
    })

    //In order to get latest image first, we just reverse the array
    imageCollection.reverse()
    
    // ADDING INSTANCES OF ‘imageObjectGroup’ HERE 
    for index in imageCollection{
        print(index);
    }
}

// The images array is where each photo instance will be stored
struct ImageObject: Identifiable {
    let id = UUID()
    let image = PHAsset()
    /// Card x position
    var x: CGFloat = 0.0
    /// Card y position
    var y: CGFloat = 0.0
    /// Card rotation angle
    var degree: Double = 0.0
}

var imageObjectGroup = [ImageObject]()
1 Answers

Why not just do:

for phAsset in imageCollection {
    let newImageObject = ImageObject(image: phAsset) /// make a new `ImageObject` 
    imageObjectGroup.append(newImageObject) /// append it
}

or this one-liner:

imageObjectGroup = imageCollection.map { ImageObject(image: $0) }

...Just make sure to change let image = PHAsset() to var image = PHAsset(), otherwise you won't be able to change the image.

Related