0
let cities = [{ "name" : "SF", "id" : 4, "population" : 10, favorite: false},  { "name" : "NY", "id" : 5, "population" : 20, favorite: false}, { "name" : "DC", "id" : 6, "population" : 30, favorite: false}

I have an array and and lets say if a user applies a filter based on the population i can filter the array by using filter method, but it gives me an other array with filtered data. In filtered array user can favorite the city and when user removes the filter i need to show the full list of cities with the favorite indicator. Problem is filtered array is a separate array and the full array doesn't know if a property was changed on the filtered array. Is there any easier way handle all this? Can i filter the main array instead of creating another one?

6
  • Are the things in your array classes or structs? Commented Dec 4, 2018 at 2:18
  • @Paulw11 Structs but it can be changed if needed Commented Dec 4, 2018 at 2:20
  • 1
    Just use classes instead of structs. classes are passed by reference. Commented Dec 4, 2018 at 2:21
  • 1
    If you make them classes then they are reference objects and therefore mutable; There will only be one object referenced by both arrays, so updating the favorite property will show in both arrays, otherwise you need to update your underlying data model and refresh the unfiltered array from that Commented Dec 4, 2018 at 2:21
  • Thats a good idea, i can try it. Commented Dec 4, 2018 at 2:22

1 Answer 1

1

Create struct of JSON

struct City {
    var name : String = ""
    var id : Int = 0
    var population : Int = 0
    var favorite : Bool = false
}

This is the array of cities

var cities = [City(name: "SF", id: 4, population: 10, favorite: false),City(name: "NY", id: 5, population: 10, favorite: false),City(name: "DC", id: 6, population: 30, favorite: false)]

Than apply filter on cities based on population == 10

var filter = cities.filter({ $0.population == 10 })

After that make favorite one of them

Ex:- filter[1].favorite = true

and also update this city favorite in the main array

cities = cities.map { (city) -> City in
    var city = city
    if city.id == filter[1].id {
        city.favorite = true
    }
    return city
}
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.