How to implement protocols and delegates in SwiftUI

Viewed 2551

I was converting one of my swift project into SwiftUI. I need to convert delegtes and protocols to SwiftUI, is it allowed in SwiftUI? or any alternative methods are there? Please help me i'm so confused in SwiftUI.

I'm calling a delegate method from one of my class, then delegate method will be present in another ViewController.

//PresenterClass

protocol SplashPresenterDelegate {
    func didFetchedSystemInfo(info: String)
}
class SplashPresenter: NSObject {
    var delegate: SplashPresenterDelegate?

    func getSystemInfo(){
         self.delegate?.didFetchedSystemInfo(info: "ResponseString") 
    }
}


// Viewcontroller class

class myViewController: UIViewController {
   .
   .
   .
}

extension  myViewController: SplashPresenterDelegate{
   func didFetchedSystemInfo(info: String){
      print("delegate called")
   } 
}

Please help me to convert this code to SwiftUI

1 Answers

Typically, SwiftUI prefers the pattern of taking callbacks rather than protocol/delegates. For instance, each button in an ActionSheet has a closure that is executed when the button is tapped.

You shouldn't just convert your code over directly, though. SwiftUI, being declarative, uses different paradigms for a lot of things. For instance, you wouldn't have a didFetchInfo method, you would just assign it to a @Published variable.

Think about having "single sources of truth", where a single variable is always correct. For example, List simply takes an array and updates when the array changes, unlike UITableView where you provide the data through numberOfRows and cellForRowAt. I don't know enough about your specific project to give more detail, but those are things to think about.

Related