Reputation: 1615
I'm using SwiftUI
with Xcode-beta 4
.
I want to create dynamic button with ForEach
. I'm using these lines of code:
struct Result {
var id = UUID()
var score: Int
}
struct ContentView : View {
let results = [Result(score: 8), Result(score: 5), Result(score: 10)]
var body: some View {
VStack {
ForEach(results.identified(by: \.id)) { result in
Button(action: {
print(result.score)
}){
Text(result.score)
}
}
}
}
}
but Xcode
can't compile this.
when I change Text(result.score)
to Text("test")
in button style, now Xcode can compile it
Upvotes: 2
Views: 5445
Reputation: 174
Since result.score is Int, you must convert it to String to show in Text(). Change your text button code to this one:
Text("\(result.score)")
Upvotes: 2
Reputation: 8183
To print an Int
: Text("\(result.score)")
Also keep in mind that the ForEach
syntax changed a little bit (Beta 5).
Now it should be: results.identified(by: \.id)
let results = [Result(score: 8), Result(score: 5), Result(score: 10)]
var body: some View {
VStack {
ForEach(results.identified(by: \.id)) { result in
Button(action: {
print(result.score)
}){
Text("\(result.score)")
}
}
}
}
Upvotes: 6