0

I need to define a property of a Class to be of Type UIViewController and to implement protocol MyProtocol. In objective-C I can write something like

UIViewController<MyProtocol> myProperty;

I can't find anything on the documentation and so I suppose that this is not possible :/ can you confirm... here is the example code to add some more info

class SignInPresenter {

    var myProperty:UIViewController and MyProtocol <--- here is the problem. 
MatterGoal
  • 16,038
  • 19
  • 109
  • 186

2 Answers2

1

You have two choices. You can either use a Generic with type constraints or use protocol extension with type constraints.

In the case of Generics it looks like:

protocol P1 {
}

class X {
}

class Y : X, P1 {
}


class Z<T: X,P1> {
    var myProp : T?
}

In the case of protocol extensions, you can use the protocol to provide the required methods and properties and use the extension to implement them for the specific case when the protocol is implemented by the class (e.g. UIViewController). This may be a better option if you don't really need to require UIViewController, but it will be used in practice. I prefer this kind of design as it allows for looser coupling.

Tom Pelaia
  • 1,275
  • 10
  • 9
-2

First, multiple protocols are defined with a comma. For example,

class SearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol

Secondly, variables do not conform to protocols. From Apple's documentation, "A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol."

jbcd13
  • 145
  • 8