Search code examples
foreachswiftuiidentifiable

Can a Swiftui Identifiable Foreach loop select only the first 5 items


Howdy I have a project that only needs to display the first 5 items in the loop of over 30 items, below is my code

struct Introductions: Codable, Identifiable {
   let id: String
   let topIntros: String?
   let image: String
   let date: String
}

ForEach(introductions) { introduction in
   NavigationLink(destination: IntroductionDetailView(introduction: introduction)) {
      IntroductionsView(introduction: introduction)
   }
}

I tried using this method but xcode crashed crashed after i scrolled past the fifth item

ForEach(introductions, id: \.topIntros) { introduction in
   NavigationLink(destination: IntroductionDetailView(introduction: introduction)) {
      IntroductionsView(introduction: introduction)
   }
}

Thanks


Solution

  • you could try something like this:

    if (introductions.count >= 5) {
        ForEach(introductions.prefix(upTo: 5), id:\.id) { introduction in
           NavigationLink(destination: IntroductionDetailView(introduction: introduction)) {
              IntroductionsView(introduction: introduction)
           }
        }
    }