I'm trying to update a textview whenever an object is added to an array and show that text in the textview like this:
"object 1"
"object 2"
the issue is that every time a new object is added to the array it overwrites the object before it so it will just show:
"object 2"
Here is the code I'm using, I'm not completely sure how to append the text so it shows all items in the array once a new item is added instead of just displaying the last item added.
struct ObjectData {
let name: String
let type: String
let code: Int
}
var updatedObjectArray = [ObjectData]() { didSet {
self.updateObjectData(object: self.updatedObjectArray)
}
func updateObjectData(object: [ObjectData]) {
for objectData in object {
self.ObjectTextView.text = objectData.name
}
}
In your for-loop, you are setting the text to a new value on every iteration, thus removing your last iteration's changes. You can append your names to a new string, then set the text at the end of the for-loop like this:
func updateObjectData(object: [ObjectData]) {
var objectStrings = ""
for objectData in object {
objectStrings += objectData.name + "\n"
}
self.ObjectTextView.text = objectStrings
}
Or a swiftier way without the ending newline by mapping ObjectData to its name and joining with a newline:
func updateObjectData(object: [ObjectData]) {
self.ObjectTextView.text = object.map({$0.name}).joined(separator: "\n")
}