I have a class
defined as follows:
class placeData: Equatable {
var description : String
var selected : Bool
init (description : String, selected : Bool) {
self.description = description
self.selected = selected
}
}
I then define an array
as follows:
var placeDataArray = Array<placeData>()
And populate it with some items:
placeDataArray = [placeData(description: "Afghanistan", selected: false), placeData(description: "Albania", selected: false)]
What I am looking to do is get the index of a description such as "Afghanistan" and then change selected
to true
from false
. indexOf
and find
methods don't seem to work, unless I am using them incorrectly.
I am also trying to filter
the placeDataArray
for true
so that all of the descriptions
with true
values will appear in the variable I set. However, I am going about this the wrong way as well. I am fairly new to swift and can't seem to figure these out. Also, the array changes with user input hence the indexing and filtering.
Thanks in advance
I think the easiest way is this:
if let index = placeDataArray.indexOf ({ $0.description == "Afghanistan" })
{
placeDataArray[index].selected = true
}
It does not require Equatable.
Similarly, you can use filter to show only selected items:
let selected = placeDataArray.filter { $0.selected == true }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.