ForEach(0..<3) {
Button {
//code
} label: {
Image(countries[$0])
}
}
This doesn't work because the initializer you are using for Button
is this one:
init(
action: @escaping () -> Void,
label: () -> Label
)
Note that the action
and label
parameters are closures, which means that $0
you are trying to use in label
actually refers to the first parameter passed into that closure, not the parameter of the ForEach
. Except, hang on, the action
and label
closures do not take any parameters. And so, you get an error.
You can see that $0
doesn't belong to the ForEach
if you add a line like so:
ForEach(0..<3) {
let _ = print($0)
Button {
//code
} label: {
Image(countries[$0])
}
}
When you do that, this error will disappear: Contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored
because you are no longer ignoring the parameter to the ForEach
.
It works here:
ForEach(0..<3) {
Text("\($0)")
}
because Text
is taking in either a LocalizedStringKey
or a String
rather than a closure, so $0
in this case refers to the parameter of the ForEach
as you would expect.
This code:
ForEach(0..<3) {_ in
Button {
//code
} label: {
Image(countries[_])
.renderingMode(.original)
}
}
doesn't work for a couple of reasons.
First is because of the same reason the first example above didn't work; you are trying to reference a parameter passed to the label
closure but that closure doesn't take any parameters.
Second, and most importantly, you can't access an array this:
countries[_]
Ultimately, you end up having to do this:
ForEach(0..<3) { number in
Button {
//code
} label: {
Image(countries[number])
.renderingMode(.original)
}
}
Hope that helps explain what's going on.