Recently, I had to get started (fast) with Swift on a series of existing iOS projects. I would classify myself as being able to get to fourth gear in a Honda Accord with a manual transmission when it comes to using and applying Swift. I look forward to the day when my Swift knowledge is equivalent to running full out on the Nurburgring in a Bugati Veyron.
My background is C, C++, C#, Objective-C, with a side of JavaScript along the way.
I will never admit to any classic Visual Basic, or VB.NET, code ever being typed by my fingers, ever!
When it comes to learning a new language, I find myself in ‘Use it or lose it’ mode. Learning Swift comes very naturally if you have a concrete task which allows you to add a feature, or refactor an existing iOS project, with brand new Swift code.
I found that becoming proficient with Swift was very easy given the general C language progression in my career. In very short order, I was able to do almost all the tasks in Swift that I would normally do in Objective-C against the CocoaTouch / UIKit API surface. More advanced Swift language constructs exist, which I have barely touched, and hope to be able to learn and apply some day—I am looking at you, protocol extensions and generics.
Swift is an expansive language with many hidden gems and great language constructs. The Swift Programming Language (Swift 2.2) iBook is over 1,000 pages (as paginated at my screen size, your mileage may vary) and has so many great samples and documented language features that your brain quickly fills up as you read through it. It may seem daunting, but, once the basics of Swift are mastered, the advanced techniques will follow.
This very rough guide is meant to expose you to the philosophy behind the Swift language and provide references to the point where you feel comfortable doing almost any task in Swift.
What follows are references, philosophy, history, and a general story of what I went through while revving up with the Swift language. You will notice I don’t have any Swift code in this post. At all. Apple does such an amazing job in the The Swift Programming Language (Swift 2.2) iBook that I recommend you just go there for all the startup samples you need. Rev up your Mac, install Xcode, rev up a Playground, put the Swift Programming Language book on Monitor 2, and get started learning Swift.
I sincerely hope that your experience is as good as mine was as I started learning Swift.
Reference and Learning
iBooks – The Swift Programming Language (Swift 2.2)
iBooks – Using Swift with Cocoa and Objective-C (Swift 2.2)
- These 2 iBooks are the definitive guide to the Swift language. They are sweeping and comprehensive and serve to build you up gradually from basics to advanced Swift language constructs.
iTunes U – Developing iOS 9 Apps with Swift by Stanford
- I cannot recommend these movies more highly. These serve as a great simultaneous companion to the Apple Swift iBooks.
Ray Wenderlich – Swift 2 Tutorial: A Quick Start
- Nobody does amazingly useful and entertaining tutorials like Mr. Wenderlich and his companions. Dig deeper at this site to find even more useful iOS code snippets.
Github – Awesome Swift – Includes tutorials and frameworks
- Yet another great list of maintained links related to Swift language ‘Get Started’ guides and Swift based Frameworks.
Subscribe to Swift Weekly
- Swift Weekly does a great job of summarizing what is happening with the constantly changing Swift language development, in addition to providing some really great links that should help you be more ‘Swifty’ with your code and thinking.
Swift Frameworks I can recommend
Github – Decodable – Translate JSON to Swift structs
- I like Decodable more than Argo + Curry and SwiftyJSON for JSON to Swift struct translation.
- IMHO: Nothing beats C# + Newtonsoft.JSON (or JSON.NET) for seamless and awesome JSON translation. But Decodable makes JSON to object conversion way easier than anything in Objective-C.
- Side note: In order to use these frameworks in your iOS project, you probably also need to become proficient with Carthage or CocoaPods based dependency management within an Xcode project.
WWDC Swift Sessions
I hate to say: “Watch them all”, but …
From WWDC 2015:
- Worth it to see how the language evolved between Swift 1.0 and Swift 2.x
Protocol-Oriented Programming in Swift
- Worth it to get exposure to a series of more advanced language features
- The focus on class vs. struct (or reference vs. value types) is also a great object lesson (pardon the pun).
- For those of you with C# experience this video is fascinating when you realize that protocol in Swift is the exact same thing as interface in C#.
Building Better Apps with Value Types in Swift
- Helps reinforce the concepts from the Protocol-Oriented Programming in Swift video.
Swift and Objective-C Interoperability
- Much of the Interoperability rules are changing with Swift 3.0. Especially naming.
Improving Your Existing Apps with Swift
WWDC 2016 promises Swift 3.0 videos and much more Swift architecture goodness.
Swift Futures
Swift is now all open source out on Github with a very active community of developers. To stay on top of things be sure to join the community and the mailing lists.
- To give you an idea regarding Swift language topics discussed:
- The community has talked about completely removing the for statement from the language and requiring a closure like replacement along the lines of map.
The Talk Show Podcast – Episode 139 – Transcript
- Craig Federighi discusses the Swift language history and future.
- There is a great follow up by John Siracusa.
Key Concepts You Should ‘Grok’
I believe that the following things are the practical takeaways from all that reference material for any starting Swift programming experience:
- Optionals and unpacking – Over the long haul, this will become the #1 thing that you are always thinking about as you program in Swift. For C programmers, Optionals and unpacking is the same as malloc and free. Every variable and member needs to be thought of in terms of whether or not to make it optional. You will get so tired of the red dot in Xcode telling you to add a ! here and a ? there. The more you grok optionals and unpacking, the less friction you will have day-to-day with the language.
- if .. let – If let is a great helper for all the optional access and value unpacking you will need to do. If let is a huge helper as you interface with legacy CocoaTouch / UIKit constructs.
- var and let – Every variable declared needs to be thought of as mutable or immutable. This concept coupled with optionals is a huge mind shift, especially for Javascript and C# programmers.
- Class vs. struct or reference vs. value types – Knowing the difference between reference and value types can help improve performance and also give you a leg up on the mutation of your object across calls. The weirdness that results when the Swift String is actually a value type (and not a reference type such as NSString*) is also an interesting brain twister.
- Closures – Closures in Swift are similar to blocks in Objective-C, however the cleaner (and possibly more complex) language handling of closures can be mind bending. This is especially true for closures as the last parameter to a function where the function call can be closed, but the closure can go on.
- Threading / Async – Unfortunately, Swift has no native language construct for async or multiple thread handling. This means that you are on your own with GCD calls, or other thread handling techniques you already do with Objective-C, only in an all new language.
- C# people will really start to miss async / await, and Javascript people will start to dislike the GCD nastiness around their closures. You can only type dispatch_get_main_queue() so many times before you start to lose more hair than a 42 year old with a bald maternal grandfather.
Philosophical and Design Takeaways
- Swift is a perpetual Beta language – I am being kind of vicious with this statement. Apple continues to evolve Swift at a rapid pace (see also the community links above). Apple has stated that they have no issues with changing the language so your code won’t compile under future versions of Swift. This is both good and bad. It is good in that Apple is very dedicated to awesome Swift futures. It is bad in that future refactoring of your code could include things like rewriting every for loop as the for keyword is rendered obsolete by the compiler.
- Swift is designed to eliminate null access crashes – Apple has tons of app crash metric data. From that metric data they learned that EXC_BAD_ACCESS is probably the #1 problem all apps suffer from. To eliminate the dreaded null access crashes, Swift is designed from the ground up to make sure that you know how every memory chunk is being accessed from each variable.
- Apple has shipped very few applications that utilize Swift code on iOS as of January 2016 – Unfortunately, this is believed to be true. As Apple really starts to ramp up on Swift, there will be more and more changes to the language, and much more stability to the language and runtime.
- Swift may not be for you, your company, or your project, yet – Your company probably has a ton of assets in Javascript, C, C++, C#, and Java. Those assets are crown jewels. You should treasure them. There are many ways to reuse those assets on iOS that won’t break the bank and require you to learn a whole new Swift based technology stack. Swift may not be for you if you don’t have any Objective-C based resources yet.
- Javascript – Take a look at React Mobile, PhoneGap, or other Javascript based app frameworks.
- C# – Take a look at Xamarin and Xamarin.iOS / MonoDroid, portable assemblies, and .NET Core futures.
- Java – Take a look at the Android platform. If you need to be on iOS take a look at J2ObjC. With all that Objective-C code generated from your Java code, you can always bring in Swift on an as-needed basis.
I come from a diverse background of technologies across Windows and iOS, front end and server side. I can say that Swift is a dramatic improvement over Objective-C on many levels. However, as with all new things that are working against 20-year-old code (and the ideas behind that code), there are going to be bugs and changes as things evolve. Sometimes it is best to use what you have, be ready for what is coming, then jump in feet first into something like the current Swift stack.
Knowing the depths of Objective-C helps you learn Swift
It is 1000 times easier to use Swift if you have a firm grounding in Objective-C.
There, I said it. Apple doesn’t want to admit it, but you can become efficient with Swift much faster if you understand all the concepts behind Objective-C.
Message passing, reference counting, automatic reference counting, strong / weak references, protocols, delegates, the whole philosophical and technological surface of CocoaTouch / UIKit, function naming conventions—All of that Objective-C knowledge will only help you ramp up rapidly on Swift.
Swift is way easier to learn if you can intuitively grok that behind all those smooth Swift wrapped CocoaTouch / UIKit calls exist a ragged, crunchy, 20-year-old Objective-C core. There are classes that still start with NS in there! NS stands for NeXTSTEP! Yes, that black cube thing from the bad Steve Jobs movie [Rotten Tomatoes Score of 74%—Maybe not so bad], of which 5,000 total were sold!
There are a ton of great Swift based frameworks out there, but for the foreseeable future you will still have to pull down Objective-C libraries and frameworks to get your real work done.
For so many tasks, nothing can substitute an Objective-C, C, C++ based approach due to the need to go ‘to the metal’ for memory management. Being able to go ‘to the metal’ lets you get the best out of pure native APIs like OpenGL, CoreAudio, and the Accelerate Framework. I don’t doubt that someday Swift will be optimal when used at those layers too, but for now the code samples and libraries that maximize certain kinds of apps are still rooted in Objective-C, C, or C++.
The great thing that Apple has done with the iOS tooling is the seamless way a single app can contain Objective-C, C, C++, and Swift code all mixed together in a single project. This is a great development story, and an amazing technological feat.
There are whole swaths of APIs within CocoaTouch / UIKit which are easier to use in Swift if you know how to exercise them in Objective-C. There is a reason that Apple’s Using Swift with Cocoa and Objective-C (Swift 2.2) reference is 81 pages long (and also well worth reading from front to back).
From the Fringe- NSClassFromString – Using Swift from Objective-C
In a recent project I wanted to use a Swift based class as a transplant into some legacy Objective-C code. The Swift class had to be instantiated using the NSClassFromString call.
I did what anyone would do, revved up my Swift class within my Objective-C project. Then tried to call NSClassFromString(“MyCoolSwiftClass”)
It didn’t work.
Well after Googling and a series of Stack Overflow articles, I stumbled onto a function and reference code that properly takes your Swift class name and makes it work via NSClassFromString.
According to Apple’s Using Swift with Cocoa and Objective-C (Swift 2.2) reference you have to include the app name into the string to use it. So NSClassFromString(“MyApp.MyCoolSwiftClass”) is the way to go.
Unfortunately, the journey doesn’t stop there. It still didn’t work.
The project I was working on had multiple build configurations, and the app name would change depending on the build configuration. So after much sadness and gnashing of teeth, I stumbled onto this Objective-C helper function thanks to Kevin Delord on Stack Overflow:
- (Class)swiftClassFromString:(NSString *)className { NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"]; NSString *classStringName = [NSString stringWithFormat:@"_TtC%d%@%d%@", appName.length, appName, className.length, className]; return NSClassFromString(classStringName); }
In Objective-C we have to go and parse out the bundle name from the main app bundle, and append that with the Swift class name in order to use our shiny new Swift class within our legacy code.
In all honesty, I don’t know what happens if you try to instantiate a Swift class that was brought in via a Framework (most likely via Carthage). The above code may not work because we are just looking at the main bundle name, not the Framework bundle name. Further investigation is needed here.
This won’t be the last time that I will need to know Objective-C in order to really use Swift effectively. Many more examples exist, and many future examples will be created, as the Swift language continues to evolve and Objective-C slowly dissolves. We are already starting to see cracks showing up in the Swift and Objective-C interoperability story via the ongoing discussions of dynamism and the Application Binary Interface (ABI).
Mix / Match of Objective-C and Swift in the same project
I am going to seek to summarize Apple’s great developer documentation in the Mix and Match section of the Using Swift with Cocoa and Objective-C (Swift 2.2) iBook.
To use Swift classes in your Objective-C files the compiler will generate a header named:
YourAppName-Swift.h
At the top of your Objective-C .m files you #import this file to use your Swift classes within Objective-C:
#import <YourAppName-Swift.h>
To use Objective-C classes in your Swift code the compiler will automatically include all headers you add to the Swift bridging header file:
YourAppName-Bridging-Header.h
You do not need to import anything within your Swift code as the bridging header will take care of all class bridging from the #import(ed) Objective-C headers for you.
The 2 header files mentioned above are part of the Build Settings of your main app project.
The file name that you add Objective-C header #import(s) to so you can use Objective-C classes in Swift code:
- Swift Compiler – Code Generation
- Objective-C Bridging Header
The file name that you #import into Objective-C files in order to use Swift types:
- Swift Compiler – Code Generation
- Objective-C Generated Interface Header Name
To use Frameworks that are referenced at the project level within your Swift code you do need to import the Framework by name at the top of your Swift file.
For example:
In the links at the top of the article I recommend the Decodable framework to translate JSON into populated Swift structs.
To use Decodable within Swift code you need to include the Framework within your project and you also have to import the Decodable framework at the top of your Swift file:
import Decodable
Good Luck!
In general, if you are starting an iOS application from scratch, and you have made the decision to go pure native with Xcode based tooling, I highly recommend learning Swift and using it from the start. Your software quality will be awesome from day 1 as you start to internalize if .. let, optionals, completion handlers, and other ‘Swifty’ techniques of doing things.
You lose nothing by starting your new application in Swift because you can always mix/match Objective-C, C, and C++ as needed throughout the development cycle.
In your existing application, I would start to try out Swift for certain non-essential components and ramp up Swift usage as your knowledge, the language, and tooling matures. I have started using Swift for wrappers around legacy Objective-C based static libraries, to standard UITableViewController implementations, and to simplify JSON to struct processing. The mix / match nature of Swift to existing Objective-C code is seamless and stable for all tasks within an existing application.
You should find that you will be writing much less code, getting more done, at a high stability level, with Swift within the first couple of weeks. The clarity and readability of your code should also be much higher as you fall into the groove of using the Swift language.
Swift really is the future of iOS and Mac OS X app development. The time is now to start learning and improving your Swift skills.
Leave a Comment