How or should I use weak self in SwiftUI coding?

Viewed 56

I tried to make a test code for learning about the use case of weak self in SwiftUI, I not sure if my example code is correct one for asking about issue, but the main goal is working with weak self with Swift/SwiftUI. I am not looking to use UIKit codes combined with SwiftUI codes, the goal is trying to learn the use case of weak self when we are working with a custom function like myTest. So let me know if I even need weak self in SwiftUI or if I need how it should be used.

struct ContentView: View {
    @State private var string: String = "tap on update"
    
    var body: some View {
        
        VStack {
            
            Text(string)
                .fixedSize()
                .padding()
            
            Button("update") {
                
                shared.myTest(result: { value in
                    string = value
                })
                
//                shared.myTest(result: { [weak self] value in
//                    string = value
//                })
            }
            
        }
        .padding()
        
    }
}

let shared: MyClass = MyClass()


class MyClass: ObservableObject {
    
    func myTest(result: (String) -> Void) {
        // some work here ...
        result(UUID().uuidString)
    }
    
}
0 Answers
Related