1

I need to declare a variable with type UIViewController that conforms to a custom protocol I made. Normally, I would do this in ObjC:

UIViewController<MyProtocol> *thingie;

But, I have no idea how to accomplish that in swift.


I'm just casting the object for now, till something useful shows up:

let conformingObject = viewController as MyProtocol
Mazyod
  • 22,319
  • 10
  • 92
  • 157
  • Does it matter whether or not the object actually is a `UIViewController`? – nhgrif Nov 23 '14 at 16:27
  • @nhgrif Yeah, I access the `UIViewController` methods as well as the protocol methods. – Mazyod Nov 23 '14 at 16:30
  • Are there objects you want to conform to `MyProtocol` that are not `UIViewController`s? – nhgrif Nov 23 '14 at 16:30
  • @nhgrif Yeah, of course, otherwise I'd use a subclass. Some are `UINavigationController`s, others `UICollectionViewController`s. – Mazyod Nov 23 '14 at 16:32
  • possible duplicate of [Swift generic variable](http://stackoverflow.com/questions/26443153/swift-generic-variable) – rintaro Nov 24 '14 at 02:41
  • related: http://stackoverflow.com/questions/26401778/swift-how-can-i-declare-a-variable-of-a-specific-type-that-conforms-to-one-or-m – rintaro Nov 24 '14 at 02:43

1 Answers1

1

You may achieve something similar by using generics. Something like this:

class SomeClass<T where T: UIViewController, T: MyProtocol> {
    var thingie: T
}
Ivica M.
  • 4,763
  • 1
  • 23
  • 16