1

I have a BaseViewController and I want to inherit from this in a subclass. When I do this the subclass "TestViewController" doesn't appear under the class dropdown in Xcode's interface builder (see below image). Isn't this possible?

class BaseViewController<T: AnyObject> : UIViewController{

    var  test: T?

    override func viewDidLoad() { }

}

class TestViewController : BaseViewController<UIView>{ }

If I just type in the class name then I get a runtime error saying:

Unknown class TestViewController in Interface Builder file

Tried

  • Removing references to files and adding them again
  • Editing the storyboard using a text editor and adding name to attribute "customClass"
jscs
  • 63,694
  • 13
  • 151
  • 195
Mat0
  • 1,165
  • 2
  • 11
  • 27

1 Answers1

2

Pretty simple: You can't use a generic type here. The reason is that UIKit is written in ObjC, and generic types are not fully visible to ObjC. This answer goes into the details.

Gregory Higley
  • 15,923
  • 9
  • 67
  • 96
  • Note that although the view controller itself can't be generic, it *can* extend a generic type and `typealias` the type to whatever it needs. – NRitH Jun 26 '17 at 20:48
  • @NRitH That's not my understanding, but I'll try it to verify. – Gregory Higley Jun 26 '17 at 20:49
  • I just had to do this myself a couple of weeks ago, so I'm pretty sure that it works. :) – NRitH Jun 26 '17 at 20:52
  • Well, let's be clear what we're talking about. Certainly you can create a generic `UIViewController` subclass and then `typealias` that subclass, e.g., `typealias FooViewController = GenericViewController`. That's no problem. But can you then _use_ that `typealias` in Interface Builder? It's the latter I'm skeptical of. In fact, if you are right, I think my answer is incorrect. – Gregory Higley Jun 26 '17 at 20:53
  • 1
    What I'm talking about is `class FooViewController: UIViewController, SomeProtocolThatHasAnAssociatedType { typealias SomeAssociatedType = Foo }`. Now the `FooViewController` shows up in the IB identity inspector. – NRitH Jun 26 '17 at 20:56
  • You're completely right that you *cannot* use the typealiased `FooViewController` that you gave in your example. – NRitH Jun 26 '17 at 20:57
  • Yes, so fortunately my answer is still correct. And yes, I was well aware that you can implement a protocol with an associated type without any trouble. This is more or less obvious (at least to me). What ObjC cares about is understanding the inheritance relationship. It will just ignore the Swift protocol. – Gregory Higley Jun 26 '17 at 20:59