Home > Back-end >  How to compare array before removing its items in SwiftUI?
How to compare array before removing its items in SwiftUI?

Time:08-21

How can i compare original items of an array before i remove them? I have an array of items that get removed every time they are showed and get added into the empty array... to avoid index out of range i was trying: if emptyArray.count < array.count { //append element } but it is not working as expected because elements of the full array get removed from it in order to be unique, so it works until the empty array contains half the elements of the full one

func changeNumber() {
        if appearedNumber.count < numbers.count { // <-- doesn't work because he lost items
            appearedNumber.append(currentNumber)
            
            let index = Int.random(in: 0..<numbers.count)
            currentNumber = numbers[index]
            numbers.remove(at: index) // remove items from full array
        }
    }

Full code

struct ContentView: View {
    @State private var numbers = ["0", "1", "2", "3", "4", "5"]
    @State private var currentNumber = ""
    
    @State private var appearedNumber = [String]()
    
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink {
                    SecondView(appearedNumber: $appearedNumber)
                } label: {
                    Text("Change view")
                }
                .padding()
                
                Text(currentNumber)
                    .font(.largeTitle)
                    .bold()
                
                Button {
                    changeNumber()
                } label: {
                    Text("Change person")
                        .font(.largeTitle)
                        .bold()
                }
                .padding()
            }
        }
    }
    func changeNumber() {
        if appearedNumber.count < numbers.count {
            appearedNumber.append(currentNumber)
            
            let index = Int.random(in: 0..<numbers.count)
            currentNumber = numbers[index]
            numbers.remove(at: index)
        }
    }
}


struct SecondView: View {
    @Binding var appearedNumber: [String]
    
    var body: some View {
        VStack {
            ForEach(0..<appearedNumber.count, id: \.self) { index in
                Text(appearedNumber[index])
                    .font(.largeTitle)
                    .bold()
            }
        }
    }
}

CodePudding user response:

You can simplify this greatly by shuffling the array...

@State private var numbers = ["0", "1", "2", "3", "4", "5"].shuffled()

then:

func changeNumber() {
    if numbers.count > 0 {
        currentNumber = numbers.removeFirst()
        appearedNumber.append(currentNumber)
    } else {
        currentNumber = "out of numbers"
    }
}
  • Related