Adding items to array with chancing boolean to true

Viewed 41
import Foundation

struct person: Identifiable{
    var id = UUID()
    var name: String
    var age: Int
    var job: String
    var myPerson: Bool
}


class personViewModel: ObservableObject{
    @Published var people: [person] = []
    @Published var myPeople: [person] = []
    
    
    init(){
        addPeople()
    }
    
    func addPeople(){
        people = peopleData
    }
    
    func addMyPeople(){
        //Code Here..
    }
    
}



var peopleData = [
    person(name: "Bob", age: 22, job: "Student", myPerson: false),
    person(name: "John", age: 26, job: "Chef", myPerson: false)
]

I am trying to do adding items to myPeople. There is a func for adding people to a array but its adding all people. I want to add only my person bool is true ones.

1 Answers
import Foundation

struct person: Identifiable{
    var id = UUID()
    var name: String
    var age: Int
    var job: String
    var myPerson: Bool
}


class personViewModel: ObservableObject{
    @Published var people: [person] = []
    @Published var myPeople: [person] = []
    
    
    init(){
        addPeople()
    }
    
    func addPeople(){
        people = peopleData
        myPeople = peopleData.filter { $0.myPerson }
    }
    
}



var peopleData = [
    person(name: "Bob", age: 22, job: "Student", myPerson: false),
    person(name: "John", age: 26, job: "Chef", myPerson: false)
]

This is the way how to fix. Thank you Jaokim Danielson for solution.

Related