Home > other >  SWIFT - Can I store functions in dictionary?
SWIFT - Can I store functions in dictionary?

Time:05-21

I am trying to make some template pages of frequently used at work. can I store function(button action) in dictionary?

'''

                        ForEach(buttonConfigure, id: \.self) { buttonConfigure in

                            Button(action: {
                                buttonConfigure["action"]!
                            }, label: {
                                HStack {
                                    Spacer()
                                    Text(buttonConfigure["text"]!)
                                        .font(.system(size: 15, weight: .medium))
                                    Spacer()
                                }
                            })
                                .frame(height: FrameSize.btnFullheight, alignment: .center)
                                .foregroundColor(Color.init(hex: buttonConfigure["foreColor"]!))
                                .background(Color.init(hex: buttonConfigure["backColor"]!))
                                .cornerRadius(6)

'''

and here is dictionary. Keys such as "text", "foreColor", "backColor" work well, but I don't know how can I make "action" key works.

'''

var buttonConfigureDict = [
    ["text": "Delete", "foreColor": "#707070", "backColor": "#E6E6E6",
     "action": "self.presentationMode.wrappedValue.dismiss()"],
    ["text": "Clear", "foreColor": "#E6E6E6", "backColor": "#1E2A52",
     "action": "self.presentationMode.wrappedValue.dismiss()"]]

'''

CodePudding user response:

You can but you shouldn’t.

Create a struct to store this data.

struct DataModel {
  let title: String
  let foreground: Color
  let background: Color
  let action: () -> Void
}

CodePudding user response:

Yes but why would you do that? A better way is to save the button in a view which you can access the view later. Or maybe a global function or static function for future use.

  • Related