return raw.value enum

hey. i am trying to make a hangman game and I want to make a grid of buttons for the letters. I did that with a enum but now my problem is I can't figure out for to return the letters value, inside the button actions. so I can later use them in the game

enum letters:String {

    case a = "a"

    case b = "b"

    case c = "c" ...  

}

 let buttons: [[letters]] = [

        [.a, .b, .c, .d, .e, .f, .g],

        [.h, .i, .j, .k, .l, .m, .n],

        [.o, .p, .q, .r, .s, .t, .u],

        [.v, .w, .x, .y, .z] ForEach(buttons, id: .self) {row in

                HStack{

                    ForEach(row, id: .self) {item in

                        Button(action: {

                             //what to put here to return the letter as string?                             

                        }, label: {

                            Text(item.rawValue)

Answered by ForumsContributor in
Accepted Answer

I suggest you create a variable somewhere in your app, probably in your data model, to hold the pressed button's value e.g. var pressedButton : letters?. Then in your Button(action: { pressedButton = item }. NOTE: if pressedButton is defined outside of this view, then you need to refer to it correctly e.g. myDataModel.pressedButton

pressedButton is defined as Optional, because to start with no button has been pressed. When your app goes to use pressedButton it needs to check that a button has indeed been pressed, i.e. pressedButton != nil. You can display the pressedButton value as pressedButton.rawValue

There are various ways of then dealing with a change to the pressedButton, e.g 1) a didSet on the pressedButton var, 2) an @ObserverableObject entity that contains @Published pressedButton

BTW, the Swift convention is that type definitions, including enums, have a name starting with Uppercase e.g. Letter and instances use an initial-lowercase name. So, in your example it would be

enum Letter : String {
case: a,b,c,d,e,f,g
}
let buttons : [[Letter]] = [
    [.a, .b, .c, .d, .e, .f, .g],

Best wishes, Michaela

return raw.value enum
 
 
Q