For some reason I can't really understand how ForEach works in Swift and I can't see where the ID that is required is really useful could someone maybe give me an example?
var emojis = ["a","a"]
var body: some View {
VStack
{
ScrollView
{
LazyVGrid(columns: [GridItem(.adaptive(minimum: 85))])
{
ForEach(emojis[0..<emojiCount], id: \.self){ emoji in
CardView(content: emoji).aspectRatio(2/3, contentMode: .fill)
}
}
}
.foregroundColor(.red)
Spacer()
HStack
{
remove
Spacer()
add
}
.padding(.horizontal)
.font(.largeTitle)
}
.padding(.horizontal)
}
var remove : some View
{
Button{
if emojiCount<emojis.count
{
emojiCount += 1
}
} label:{
Image(systemName: "plus.diamond")
}
}
var add : some View
{
Button{
if emojiCount>1
{
emojiCount -= 1
}
} label:{
Image(systemName: "minus.diamond")
}
}
}
struct CardView: View{
@State var isFaceUp: Bool = true
var content : String
var body: some View{
ZStack {
let shape = RoundedRectangle(cornerRadius:20)
if isFaceUp
{
shape.fill().foregroundColor(.white)
shape.strokeBorder(lineWidth: 3)
Text(content).font(.largeTitle)
}
Like here for example(I know the code isn't complete and I know that this is really bad code but this is from a video) when I click on one CardView because both of them have the same ID both cards flip over even though I only clicked on one. But why is exactly is this happening? I guess I just don't fully understand how ForEach really works but to me it seems like a for loop and if it's just iterating over the emoji array and making a cardview for each string 1. Why is an ID necessary? 2. Why does clicking only one CardView flip them both over? I mean I for loop over the array and make a CardView for emojis[0] and another for emojis[1] they are both 2 different CardView's aren't they?