skip to Main Content

If i have an array like this:

@State private var names = ["Steve", "Bill", "Elon", "Jeff", "Michael"]

and i remove its items onAppear, how can i get the original names.count value despite the elements being removed?

I tried creating a copy this way: var namesCopy = names but it’s just a reference and i ended up with 2 variables referencing the same array

2

Answers


  1. We can use original as separated storage, like

    let original = ["Steve", "Bill", "Elon", "Jeff", "Michael"]
    @State private var names = [String]()
    

    and filter to set names as we need

    .onAppear {
      names = original.filter { ... }   // choose from original as needed
    }
    
    Login or Signup to reply.
  2. You’d have something like this:

    @State private var names = ["Steve", "Bill", "Elon", "Jeff", "Michael"]
    @State private var originalCount: Int? = nil
    
    .onAppear {
        originalCount = names.count
        
        names.removeAll()
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search