ios 更新/更改数组值 (swift)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34898821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
update/change array value (swift)
提问by Aldo Lazuardi
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 that code, let's say i have 5 datas:
从该代码中,假设我有 5 个数据:
- 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's croppedImagevalue?
如何更改/更新 img3 的croppedImage值?
回答by Hermann Klecker
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 with userId
"img3".
这将使用userId
“img3”更改 dataImage 对象的值。
Does this answer your question?
这回答了你的问题了吗?
If you need to search for a specific value in userId, then you are far better of with a dictionary (associated array) rather than an (indexed) array.
如果您需要在 userId 中搜索特定值,那么您最好使用字典(关联数组)而不是(索引)数组。
var datas = [String, dataImage]()
...
self.datas["img\(counter+1)"] = ...
And you access it the same way.
您以相同的方式访问它。
self.datas["img3"].value = 2.0
And please rename the class imageData into ImageData. Class names start with capitals.
并将类 imageData 重命名为 ImageData。类名以大写开头。