Working with both Swift and Objective-C - dummies

Working with both Swift and Objective-C

By Jesse Feiler

Part of Swift For Dummies Cheat Sheet

As of the start of 2015, almost all of the Cocoa and Cocoa Touch frameworks are written in Objective-C, and Swift can use them easily. (Of course it can; this was one of Swift’s design goals.) Even so, some aspects of the frameworks work well in Swift, but perhaps not as elegantly as you might like. In particular, these include the issues involved with passing pointers (used a great deal in the Objective-C frameworks) to and from Swift.

A related issue is the use of nil (as in nil pointers). Swift addresses this issue with the use of optional types — types such as Int?, which are related to non-optional types such as Int but which can accept the value of nil. (Sometimes optional types are called nullable types.) In Swift, you can unwrap an optional to deal directly with the underlying value that may be nil. You unwrap an optional value of type Int? by using an exclamation point, as in myOptional!.

Although developers inside Apple have been working with Swift for several years, most programmers only have half a year’s experience with the new language. In this short time, many developers have remarked on the fact that you still need to know a good bit about Objective-C to use Swift. How much you’ll need to know is hard to say, since virtually everyone who uses Swift today is already highly experienced with Objective-C. The experienced coders notice the pieces of Objective-C peeking through the Swift code.

If you’re starting from scratch, though, it’s fair to say you’ll need what linguists call a passive knowledge of Objective-C (meaning you can read and understand it) before you can develop an active knowledge of Swift (meaning you can read, understand, and write it).