3

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

6
  • Protocols are a core part of the swift language and is of course allowed when using SwiftUI. Delegate is a design pattern that also can be used anytime but it is not part of SwiftUI while it was well used in UIKit. Most likely you would want to use a property wrapper here like @State Commented Aug 5, 2020 at 7:24
  • @JoakimDanielson i have updated my question with code, can you please give a solution? Commented Aug 5, 2020 at 7:26
  • The SplashPresenter/Delegate can be used in SwiftUI code as-is. Show your SwiftUI code where you need that presenter. Commented Aug 5, 2020 at 7:27
  • @Asperi i want to convert my MyViewcontroller extension to swiftUI to get delegate from splashpresenter Commented Aug 5, 2020 at 7:28
  • You can take closures as parameters in your ViewRepresentables to satisfy related delegate methods. Commented Aug 5, 2020 at 9:55

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.