Marcus Rossel Marcus Rossel - 2 years ago 77
Swift Question

What use does NonObjectiveCBase have?

I was reading a blog post by @AirspeedVelocity, which mentions the

class. And since I had a little bit of a hard time following which properties/methods of this type were being accessed, I decided to check it out a bit.

The type inherits as follows:
enter image description here

So naturally I was interested in
, and played around with them a bit.

My first endeavor was simply creating a class which inherits from
. So I tried it the following way:

class Example: NonObjectiveCBase {
var value: Int

init(value: Int) {
self.value = value

This gave me the error:
super.init isn't called before returning from initializer

So of course I simply added a

init(value: Int) {
self.value = value

This now gave me the following error though:
NonObjectiveCBase' does not have a member named 'init'

So I checked the documentation on
, and indeed it has no public methods or properties. The only thing said about it is:

A common base class for classes that need to be non-@objc, recognizably in the type system.

My question is therefore: What use does
And furthermore, how could I create a sub-class if I'm supposed to call
, which doesn't exist?

Answer Source

The short answer is you probably can't inherit from this outside of stdlib. It looks very much like something Apple needed for special cases, but did not make a generally-available solution. (Swift 1 had lots of things in stdlib that you couldn't actually implement yourself because it relied on some weird _-prefixed protocol. Swift 2 does this less, but still has a bit of it.)

Because there are public children of NonObjectiveCBase (such as ManagedBuffer), the superclass must be public. That doesn't mean that it has to have a public initializer. I've used similar techniques myself to allow me to return types that I don't want the caller to be able to instantiate (because they have weird preconditions or require even more private types to construct.)

In terms of why it exists, if history is any guide, it's a matter of optimizations. The optimizer can do certain things when it can be absolutely certain of various preconditions. Sometimes the optimizer isn't as smart about proving those preconditions as Apple would like (consider SinkType, which explicitly told us it was around for situations where the optimizer gets confused). For the most part, Apple hasn't been making its special "because the compiler isn't good enough yet" tools available to us, which makes sense. As they improve the compiler, they don't want a lot of people to have written code that was closely tied to old implementation details. When Swift settles down more, I hope that Apple makes certain that we could all rewrite stdlib in "normal" Swift, but in the meantime, I accept that it's in flux.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download