Home > Software design >  How to get array's original value in SwiftUI?
How to get array's original value in SwiftUI?

Time:08-24

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

CodePudding user response:

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
}

CodePudding user response:

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()
}
  • Related