Crystal Crystal - 1 year ago 68
Swift Question

When to subclass NSObject in Swift

I just started reading about Swift. Used to do objective-c here and there a few years ago and I had a dumb question. When in Swift should you or shouldn't you subclass NSObject? Are there any best practices out there about it?

In a playground, I can do this:

public class Printer {
public func SaySomething(s : String) {
print(s);
}
}

var pr = Printer()
pr.SaySomething("yo");


That all works as expected. However, I thought I would get practice in swift by creating a Cocoa Touch Framework. So I created Printer.swift, copied and pasted the class you see above. Then in the TestLibraryTests file I tried instantiating a Printer. So I did

var p : Printer = Printer()


I got the error,
Printer cannot be constructed because it has no accessible initializers.


So I added
init() {}
.

public class Printer {
init() {}
public func SaySomething(s : String) {
print(s);
}
}


Still didn't build. I got the same error. Then once I said Printer was a subclass of NSObject, everything worked. Why is that? Is there any time you should not subclass from NSObject at this point?

Answer Source

As was stated in the comment from matt, your issue was not one of NSObject. In swift the there are three access levels if you will. Private, Within Module, and Public. If you do not decorate a property, method, class, etc... the default is Within Module. That means it is accessible to anything in the same target.Since you were running code in the test (which has a different target) you only have access to things which are explicitly Public.

Your class was Public, which is how you were able to import it. However your default init, which you get for free is the default. Therefore, outside of your target, the test has no access to the init. NSObjects init is clearly Public, so when you subclassed from it, you got a Public init.

I'd refer to the NSObject Class Reference to see what it gives you when you inherit from it. It's my feeling that in a lot of cases, it won't be required, especially if you not interoperating with a lot of Objective C.

Which then leads to the question, do I need a class, or should I use a struct?

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