Home > Mobile >  Multiple delegate in one class - Swift 5
Multiple delegate in one class - Swift 5

Time:07-10

Is it okay to have multiple delegate reference in one file. Maybe this is a dumb question, but I just want to know if theres pros or cons if I did this. Thank you.

protocol SampleDelegate1: AnyObject {}
protocol SampleDelegate2: AnyObject {}

class Sample {
    weak var delegate1: SampleDelegate1?
    weak var delegate2: SampleDelegate2?
}

CodePudding user response:

Sure, why not, if it's useful for something you're doing? It's not that unusual. A WKWebView has two delegates:

https://developer.apple.com/documentation/webkit/wkwebview

However, if the goal is to notify multiple objects of the same thing, that sounds more like an NSNotification architecture or similar.

CodePudding user response:

Yes, you can have multiple protocols, if needed. It might be illustrative to consider a few UIKit patterns:

  • Table views and collection views have distinct protocols with different functional purposes, one for “data sources” and another for “delegates”.

  • URLSession employs a slightly different pattern, with a single delegate reference, a URLSessionDelegate, which has a hierarchy of different subprotocols to cover different functional needs (e.g., URLSessionTaskDelegate inherits URLSessionDelegate, etc.).

While different situations call for slightly different approaches, the idea is that a complicated interface can be broken down into different protocols (and optionally, either separate protocol references or single one) which cover distinct functional needs.

But you say:

Actually, my only purpose is to pass data to multiple view controller. I have a sign up function and when this is triggers, I am passing data to view controllers. my problem is I have 2 types of sign up, sign up for individual and sign up for corporate that is sharing a single sign up function. I only want to pass data to the view controllers that are related to the sign up type. I thought creating two delegates will solve my problem, delegate just for individual sign up and corporate signup.

It is really hard to be specific on the basis of so little information, but on the surface, this doesn’t sound like a compelling use-case for multiple protocols, much less separate delegate references. The difference here is not different functional domains, but rather slightly different payloads (a “user” vs “corporate” account type).

I might advise a single protocol that passes back an “authentication” object which includes a “user type” or “permissions structure”, in which the caller determines “oh, on the basis of the returned authentication result I will transition to such-and-such view” or what have you. But to the extent the sign-up can stick with a single protocol/interface, keeping objects as loosely coupled as possible, the better, IMHO.

  • Related