[英]Override old object in array swift ios
I have an array of custom objects. 我有一组自定义对象。 For simplicity, lets say each object has 3 properties :
id
, timestamp
and text
. 为了简单起见,假设每个对象都有3个属性:
id
, timestamp
和text
。 I am now obtaining a JSON response from my server which contains updated text
for my objects in the array. 现在,我从服务器获取JSON响应,其中包含数组中对象的更新
text
。 I need to do the following : 我需要执行以下操作:
id
from my array. id
的对象。 text
of the object to the updated text
WITHOUT changing any of its other properties. text
设置为更新的text
无需更改其任何其他属性。 I have found the following extension which allows me to find the object in my array. 我发现了以下扩展名,该扩展名使我可以在数组中找到对象。
extension CollectionType {
func find(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element? {
return try indexOf(predicate).map({self[$0]})
}
}
I am then using the following logic to obtain the item from the array. 然后,我使用以下逻辑从数组中获取项目。
let my_object = questionImageObjects.find({$0.id== myId})
Now I set the text using my_object.text = currText
. 现在,我使用
my_object.text = currText
设置文本。
The last step is to override the old object in the array with the updated one. 最后一步是用更新的对象覆盖数组中的旧对象。 This is where I am stuck.
这就是我卡住的地方。
The extension find
will return a copy of the original struct. find
扩展名将返回原始结构的副本 。 Whatever you do to it, the original won't be affected. 无论您做什么,原始文件都不会受到影响。 You can modify it through the index:
您可以通过索引对其进行修改:
struct DataModel: CustomStringConvertible {
var id: Int
var timestamp: NSDate
var text: String
init(id: Int, timestamp: NSDate, text: String) {
self.id = id
self.timestamp = timestamp
self.text = text
}
// For debug purposes
var description: String {
get { return "( id = \(id), timestamp = \(timestamp), text = \(text) )" }
}
}
// Initial data
var arr = [
DataModel(id: 1, timestamp: NSDate(), text: "Anakin Skywalker"),
DataModel(id: 2, timestamp: NSDate(), text: "Luke Skywalker")
]
// Now the server returns a JSON that says Anakin has turned to the Dark Side
let jsonString = "{ \"id\": 1, \"text\": \"Darth Vader\" }"
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
let json = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
// Update the text
if let dict = json as? [String: AnyObject],
let id = dict["id"] as? Int,
let newText = dict["text"] as? String,
let index = (arr.indexOf { $0.id == id }) {
arr[index].text = newText
}
print(arr)
If those if let
s confuse you, here's a step-by-step guide: 如果
if let
您感到困惑,请按以下分步指南进行操作:
if let dict
checks that the JSON can be converted into a Dictionary if let dict
检查JSON是否可以转换为Dictionary let id
checks that it has an id
key of type Int
let id
检查它是否具有Int
类型的id
密钥 let newText
checks that it has a text
key of type String
let newText
检查它是否具有String
类型的text
键 let index
checks that the array contains an element with that id
let index
检查数组是否包含具有该id
的元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.