Search code examples
iosobjective-cswiftfactory-patternswift-protocols

how do I keep a reference to a class object conforming to a protocol in Swift


Perhaps I'm still thinking in an Objective-C kind of way. I'd like to register classes to be used in a factory pattern. The classes conform to a protocol such as:

protocol URLNavigation: class {
  static func canHandle(url: URL) -> Bool
  static func instantiate(with url: URL) -> UIViewController?
  var url: URL? { get set }
}

and then in my Factory class have something like:

var registeredTypes: [UIViewController.self & URLNavigation]

But I know the line above is incorrect. I'm trying to keep a references to class objects that will be used to instantiate instances of those classes.

And am also wondering how I would instantiate these using an element in this 'registeredTypes' array.

I hope it's clear what I'm trying to accomplish. Perhaps there's another approach?


Solution

  • You can do like this.

    var registeredTypes: [(UIViewController & URLNavigation).Type].