How to use closure in SwiftUI?

Viewed 39

I would like to custom a View and add a function with closure.

Like this:

public func onTapGesture(count: Int = 1, perform action: @escaping () -> Void) -> some View

It appears as an error Cannot assign to property: 'self' is immutable when I declare a function, like this:

    var onFinishedClosure: (() -> Void)?

    func onFinished(perform action: @escaping () -> Void) -> some View {
        self.onFinishedClosure = action
        return self
    }

Thanks for your help.

2 Answers

Assuming it is a modifier, you need a copy, like

func onFinished(perform action: @escaping () -> Void) -> some View {
    var modifiedView = self                  // << here !!
    modifiedView.onFinishedClosure = action
    return modifiedView
}

You get the error, because after initialising a struct, its variables can’t be changed by itself.

To change this, you can use mutating:

mutating func onFinished(perform action: @escaping () -> Void) -> some View {
  self.onFinishedClosure = action
  return self
}
Related