WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Day 91 Flashzilla challenges: Can't seem to reAdd a Card successfully

Forums > 100 Days of SwiftUI

I'm having a problem with the second challenge:

  1. Add a settings screen that has a single option: when you get an answer one wrong that card goes back into the array so the user can try it again.

I created a settings screen and with a Toggle that changes the setting. This was no problem. But whenever I try to add a card back into the cards array, I get strange behavior, such as the wrong card displaying, and then the cards becoming untappable.

For testing purposes, I'm just trying to add every card that gets removed in my removeCard function:

func removeCard(at index: Int) {
        guard index >= 0 else { return }

        let tempCard = cards[index]
        cards.remove(at: index)
        cards.insert(tempCard, at: 0)

        if cards.isEmpty {
            isActive = false
        }
    }

I've been able to successfully add new cards to the [cards] array by using the .insert function with a button anywhere inside ContentView like so:

VStack {
                HStack {
                    Button(action: {
                        self.cards.insert(self.cards.last ?? Card.example, at: 0)
                    }) {
                        Image(systemName: "gear")
                            .padding()
                            .background(Color.black.opacity(0.7))
                            .clipShape(Circle())
                    }

However, every attempt I make to add a card back into the array as a part of removeCard causes issues. What am I missing here?

1      

I found a solution which seems to indicate that there is an issue with removing/adding things to the cards array back-to-back. The solution (credit to Petro Onishchuk - YouTube) was to use DispatchQueue in order to delay the addition of the new card until after the the removal has had time to complete. 0.5 seconds seems to work.

func removeCard(at index: Int, isCorrect: Bool) {
        guard index >= 0 else { return }
        let tempCard = cards.remove(at: index)

        if reshuffleWrongAnswers && !isCorrect {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.cards.insert(tempCard, at: 0)
            }
        }

        if cards.isEmpty {
            isActive = false
        }
    }

However, this still has some major issues.

  1. Anything LESS than 0.4 seconds added to the .now() deadline will still cause problems.
  2. Anything 0.4 seconds or MORE creates a window between when the card is removed and the card is readded where swiping the next card breaks the cards stack. The greater the delay, the more likely it is to break.

Any recommendations for how to truly solve this?

1      

I was bored so I decided to make a simple test with another array that removes an element and and re-inserts it immediately. This works fine, so there must be something specific to the the CardView that is causing problems.

struct ContentView: View {
    @State private var people = ["Anna", "Barb", "Calvin", "Doug"]

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach(people, id: \.self) { person in
                        Text(person)
                    }
                }
                Button("Bingo Bango", action: { self.removePerson() })
            }
        }
    }

    func removePerson() {
        let tempPerson = people.remove(at: people.count - 1)
        people.insert(tempPerson, at: 0)
    }
}

3      

@ZoydWheeler Thank you very much for sharing this. Faced a similar problem a spent hours until found this article.

1      

Try passing the cards array directly into ForEach rather than passing a range.

ForEach(cards, id: \.self) { card in
  // etc
}

That does require making other changes, of course, like making the Card struct implement Hashable. I'm perfectly willing to believe there's a superior approach, but it's working well enough for me to move on.

1      

Hi @stuartisaac ,

I had the same problem, so I refactored my code to use

ForEach(cards) { card in
   CardView(card: card) { ...

but the problem remains: looks like SwiftUI is not aware of the change of the

@State private var cards = [Card]()

when removal and insert are done near each other... but I can't figure out why...

The only approach that works for me is the one from @ZoydWheeler, delaying adding back the card to the stack with

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  self.cards.insert(tempCard, at: 0)
}

However...

testing the two acessibility buttons, I noticed that they work correctly: when pressing the "xmark.circle" button for wrong answer the card is added back to the stack AND shown correctly without the need for delay.

Also:

when no more cards are shown on screen the timer is continuing and if I tap the "checkmark.circle" button enough times to remove the recycled cards, the games stops correctly!

Looks like the reused cards are there, but somehow not shown... could be something wrong with the layout? (e.g. why am I seeing the accessibility button after clicking something even if no accessibility features enabed?)

1      

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.