Home > Net >  Show specific items in a ForEach loop in Swift
Show specific items in a ForEach loop in Swift

Time:08-17

I am very new to Swift and coding in general and I have a question about accessing specific items in an array. I want to only show two items(creatures) from the creatures array in my view instead of returning all of the items. How would I go about doing this?

Here is the view where I want to show only two items(creatures):

struct PlayingCreatures: View {

    
    @EnvironmentObject var data : CreatureZoo
    
    var body: some View {
        
//        Want to only show 2 animals on this screen
            VStack {
                ZStack {
                    ForEach(data.creatures) {creature in
                        Text(creature.emoji)
                            .resizableFont()
                            .offset(creature.offset)
                            .rotationEffect(creature.rotation)
                            .animation(.spring(response: 0.5, dampingFraction: 0.5), value: creature.rotation)
                            .animation(.default.delay(data.indexFor(creature) / 10), value: creature.offset)
                     
                    }
                }
       
                .onTapGesture {
                    data.randomizeOffsets()
                }
           
            }
    }
}

Here is the view where the data is stored:

class CreatureZoo : ObservableObject {
    
 @Published var creatures = [
        Creature(name: "Gorilla", emoji: "           
  • Related