Update / change array value (fast)

Data model

class dataImage { var userId: String var value: Double var photo: UIImage? var croppedPhoto: UIImage? init(userId:String, value: Double, photo: UIImage?, croppedPhoto: UIImage?){ self.userId = userId self.value = value self.photo = photo self.photo = croppedPhoto } } 

View controller

 var photos = [DKAsset]() //image source var datas = [dataImage]() var counter = 0 for asset in photos{ asset.fetchOriginalImageWithCompleteBlock({ image, info in // move image from photos to datas let images = image let data1 = dataImage(userId: "img\(counter+1)", value: 1.0, photo: images, croppedPhoto: images) self.datas += [data1] counter++ }) } 

from this code, let's say I have 5 data:

  - dataImage(userId: "img1", value: 1.0, photo: images, croppedPhoto: images) - dataImage(userId: "img2", value: 1.0, photo: images, croppedPhoto: images) - dataImage(userId: "img3", value: 1.0, photo: images, **croppedPhoto: images**) - dataImage(userId: "img4", value: 1.0, photo: images, croppedPhoto: images) - dataImage(userId: "img5", value: 1.0, photo: images, croppedPhoto: images) 

How to change / update img3 croppedImage value ?

+6
source share
1 answer
 self.datas[2] = dataImage(userId: "img6", value: 1.0, photo: images, croppedPhoto: images) 

This will replace the 3rd object in the array with a new one.

or

 self.datas[2].value = 2.0 

This will change the value of the dataImage object using userId "img3".

Does this answer your question?

If you need to find a specific value in userId, then you are much better with a dictionary (associated array), not an indexed array.

 var datas = [String, dataImage]() ... self.datas["img\(counter+1)"] = ... 

And you get access to it the same way.

 self.datas["img3"].value = 2.0 

And rename the image of the imageData class to ImageData. Class names start with capitals.

+9
source

All Articles