0

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

1
  • 1
    It is Swift convention to name your classes starting with a capital letter Commented Oct 20, 2015 at 1:46

1 Answer 1

3

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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.