Import statements

Your .swift files must import frameworks in order to use them, but we don't necessarily need to import the whole of Cocoa.

If you have, for example, a model class that has no need of interacting with any UI elements (and a model class should certainly not be interacting with UI elements), you don't need to import Cocoa, Foundation will suffice:

import Foundation 
class MyFoundationClass: NSObject
{
var someDate = Date()
}

So here, MyFoundationClass is using the NSObject class and the Date class, both of which require Foundation. If you comment out the import statement, you'll get two errors, with the compiler complaining it doesn't know what those two classes are:

This is in contrast to the MySwiftClass we created previously. That class declared only an Int property, which is part of Swift, not Foundation, and also declared no Foundation superclass. So there was no need to import Foundation.

If our class needs to use user interface classes, which are not included in Foundation, such as the NSColor class, we need to import the AppKit framework:

importAppKit 
class MyAppKitClass: NSObject
{
var someColor = NSColor.red
}

Here again, if you see something like the following screenshot, you've probably used the wrong import statement (most likely Foundation):

Since AppKit imports Foundation itself, there is no need for us to explicitly import it.

If we also need a framework such as Core Data (more of which is in Chapter 9, Getting More from Interface Builder), which is not the case here, we would need to import Cocoa in its entirety.

Foundation is imported by AppKit, which is imported by Cocoa.

So now that we have a grasp of why we need Foundation and how to make sure we can subclass NSObject when we need to, we can turn to another idiom of Cocoa programming, one that is very widely used and can save you a lot of coding, key-value observing.