UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Rock Paper Scissors - Creating Buttons in ForEach Produces Error

Forums > 100 Days of SwiftUI

In this article, Paul mentions that buttons can be created with sytax like:

Button("Button 1") { }

However, when I try to do this inside a ForEach, I get an error.

  • Why is syntax for naming buttons different in ForEach?
  • How do I resolve this issue to create 3 buttons in a loop?

My code below:

let userOptions = ["Rock", "Paper", "Scissors"] ... HStack { ForEach(0..<3) { number in Button(userOptions[number])}}

I get the same error if I try:

ForEach(userOptions, id: \.self) { Button($0)

Error message: Cannot convert value of type 'String' to expected argument type 'PrimitiveButtonStyleConfiguration'

Appreciate any help on this!

2      

You do not quite match Paul's example.

Try this

HStack {
    ForEach(0..<3) { number in
        Button(userOptions[number]) { }
    }
}

The button needs an action. In this case I have put an empty action in the closure { }.

You will need to determine if an action, if any, is needed for your intended functionality.

3      

@Greenamberred - that worked, thank you!! :D

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.