LAST CHANCE: Save 50% on all my Swift books and bundles! >>

Day 91 - #3 challenge (reinserting card if wrong)

Forums > 100 Days of SwiftUI

Hi everyone,

so I found a really simple solution to this problem we all have. I see there are solutions with DispatchQueue and that's great but there is delay that you need to have for it to work.

I have found a better solution for that problem and you do not need to use DispatchQueue. It is pretty much simple. Here are the steps:

  1. You need to make Card struct conform Identifiable

    struct Card: Codable, Identifiable {
    var id = UUID()
    let prompt: String
    let answer: String
    static let example = Card(prompt: "What is capital city of Croatia?", answer: "Zagreb")
  2. You need to create a function that will get you a index from your card. Here is my solution of that function but you can make it different

    func getIndex(of card: Card) -> Int {
        for i in {
            if cards[i].id == {
                return i
        return -1
  3. When you have that function you can change your ForEach and simplify it

    ForEach(cards) { card in
  4. And to finish all up, wherever you need index you just call your getIndex(card: card) function. And that's it! Here is finished ForEach:

    ForEach(cards) { card in
          CardView(card: card) { isCorrect in
              if !isCorrect {
                  withAnimation {
                      let newCard = Card(id: UUID(), prompt: card.prompt, answer: card.answer)
                      cards.remove(at: getIndex(of: card))
                      cards.insert(newCard, at: 0)
              } else {
                  withAnimation {
                      removeCard(at: getIndex(of: card))
          .stacked(at: getIndex(of: card), in: cards.count)
          .allowsHitTesting(getIndex(of: card) == cards.count - 1)
          .accessibilityHidden(getIndex(of: card) < cards.count - 1)

Keep it going!


You dont' still need/want the id: in the ForEach? I have this ForEach(cards, id: \.id) { card in }


You dont' still need/want the id: in the ForEach?

No, we no longer need it because we made our Card struct confrom to Identifiable. With that change, ForEach knows that our cards in the Card array each have a unique id identifier, so we don't need to specify it explicitly.

See this lesson from Day 37.


Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

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

Reply to this topic…

You need to create an account or log in to reply.

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.