0

I am using this down code but xCode doesn't compile even due to: enter image description here

struct ContentView: View {
    
    @State private var stringOfText: String = "Hello, world!"
    let action: () -> Void = { stringOfText = "updated!" }       // <<: Here
    
    var body: some View {
        
        Text(stringOfText)
            .padding()
        
        Button(action: action, label: {
            Text("update")
        })
        
    }
}
ios coder
  • 1
  • 4
  • 31
  • 91

1 Answers1

0

Define it as a function:

struct ContentView: View {
    
    @State private var stringOfText: String = "Hello, world!"
    
    func action() {
        self.stringOfText = "updated!"
    }
    
    var body: some View {
        
        Text(stringOfText)
            .padding()
        
        Button(action: action, label: {
            Text("update")
        })
        
    }
}

Related SO about capturing self during init (which is what your original code is doing by defining a closure in a property like that): Referencing self in super.init In short, it's a complicated thing, and requires tricky thinking to avoid. But, luckily something like just defining it as a function here doesn't seem to have any downside.

jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • But what if we want use closures? as we can see on Button initializer method, we can define a closure like: **() -> Void** and IMHO I know the reason of error I just wanted make it to work – ios coder Feb 12 '21 at 22:41
  • 1
    Check out the link I posted -- it's different because it's in the initializer. – jnpdx Feb 12 '21 at 23:04