Search code examples
iosswiftswiftuishorthand

Swift Shorthand for Functions like Flutter?


I was writing out a SwiftUI Button and I was wondering if there's a way I could turn something like this ⤵

Button(action: {
  self.textField.value?.becomeFirstResponder()
})

into ⤵

Button(action: => self.textField.value?.becomeFirstResponder())

Clarification

self.textField.value?.becomeFirstResponder() is not a Void function. It is a function of type () -> Bool. But it's just used as an example in the answer below.


Solution

  • Button action is of type () -> Void:

    public init(action: @escaping () -> Void, @ViewBuilder label: () -> Label)
    

    So if your function also is of type () -> Void:

    func buttonAction() {
        // ...
    }
    

    you can just do:

    Button(action: buttonAction) {
        Text("Button")
    }
    

    Otherwise you need to stick what you've already tried or use another init.