CHAPTER 18: Interoperability with Objective-C
167
Note You can’t import C++ code directly into Swift, you have to export your code wrapped in an Objective-C interface.
The process of importing Swift code into Objective-C works similarly.
Interoperability What happens when you import Objective-C code into Swift? First, pointers are mapped to Swift optionals. So NSString *myString = nil
will be imported as: var myString : NSString? = nil;
Actually, that’s not strictly true. The second thing that happens is that certain types, such as NSString, are mapped to native Swift objects such as String, so the actual mapping is: var myString : String? = nil;
The Objective-C type id is mapped to the Swift AnyObject protocol. This protocol can represent an instance of any object type, just as id represents any object in Objective-C. id myObject = nil; var myObject : AnyObject? = nil var myObject1 : AnyObject = NSString()
Note The AnyObject protocol represents a safe object. If you’d like to be able to assign a nil value, it has to be boxed in an optional.
Keep in mind that, in Swift, once a variable is assigned a type, you can’t change the type of that variable. AnyObject is different, however. It can hold different types of objects. var myObject : AnyObject = NSString() myObject = NSArray()
Since AnyObject does not represent a specific type, you are allowed to call any Objective-C method or access any property without having to cast the type to specific class. var myObject : AnyObject = UIView(frame: CGRectZero) var myView = UIView() myObject.addSubview(myView)