Slug ben sandofsky cover?fm=jpg&fl=progressive&q=75&w=300

Is It Time for Swift?

Developers are drawn to new technology like moths to a flame. What could possibly go wrong? Let’s mute the hype, and use an objective approach to adopting Swift, like any new technology. How do you assess risk? How long should you wait? How do you move your team over? Ben Sandofsky covers the risks and rewards of adopting Swift over Objective‑C, & answers the great question: Is it time for Swift?


I give the standard disclosure that you might be in a small company, moving fast; and my advice may not apply to you, but hopefully someday it will.

This Seems Familiar… (00:32)

Today we are going to be talking about an exciting new runtime from Apple with strong developer momentum that makes code faster and safer.

Introduced in 1998: Steve Jobs talking about how OS X is going to be the best platform for running this exciting new runtime. They promised the fastest way to run your Java apps.

Introduced in 2008 as the future of Cocoa development: MacRuby. Based on LLVM, brings modern best practices to Cocoa development in a seamlessly bridged runtime.

Now, is it time for Swift?

Is It Time for Swift? (01:04)

Swift has reached a critical mass. If you look at the TIOBE Index of popularity among programming languages, Swift has ascended above Objective‑C. Between the two, Pascal. Ryan Olsen downloaded the top 100 apps in the App Store to see how many are running any Swift: 11% are.

Don’t Listen to the Internet (02:54)

Last July, some architects at a larger company were going to take a wait-and-see approach. It was a bit frustrating, and I let out a tweetstorm. Three months later, someone was quoting me. But do not listen to the internet. Make your decisions based on objective view points, balancing risk and rewards.

What is the Best Thing That Could Happen? (03:35)

New technology: the code will magically write itself. But no one has measured a particular language that is significantly more productive than anther. In a previous paper, they came up with 80 implementations of the same program (C, C++, Perl, Python, Rex, Tcl, etc.). You can implement the same simple trivial program faster than if you are using a more heavyweight language (Java, C++, C); those languages are more performant and use less memory.

Syntax Doesn’t Move the Needle; It’s All About Tradeoffs (04:48)

All the scripting languages were clustered in the same area; the more heavyweight languages, deeper on the further end (although they were not monitoring the maintainability of the code: Python might shine more than Perl). But syntax does not matter that much. Python, Ruby, Perl, probably have similar productivity. But a major changer in productivity is the tradeoff you are choosing. Garbage collected language, less memory management.

Get more development news like this

Swift makes the same design tradeoffs as Objective‑C. Still dealing with reference counting (instead of a GC). Still dealing with UIKit. How can I offload animation to Core Animation (as opposed to a timer firing once every 16 milliseconds)? The syntax changes, but the overall complexity of your app will (roughly) be the same. Swift will probably be only slightly more productive.

You may have read: Company X rewrote XX in YY language, and they just loved it!. That is key here: they rewrote their app. If you come back to an app later, and you already know all the business requirements, you are going to write a leaner app. Indeed, an engineer from Lyft said, “We would have built a different app if we’d started over.”

In sum, if you are trying to rewrite, that is a orthogonal issue from choosing a new language. Maintaining parity with your old app without any regressions will be challenging. Tackle one thing at a time. But I do think there are material advantages to switching over.

Let’s Play: Spot the Bug (07:26)

hashOut.data = hashes + SSL_MD5_DIGEST_LEN;
hashOut.length = SSL_SHA1_DIGEST_LEN;
if ((err = SSLFreeBuffer(&hashCtx)) != 0)
    goto fail;
if ((err = ReadyHash(&SSLHashSHA1, &hashCtx)) != 0)
    goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &clientRandom)) != 0)
    goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
    goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
    goto fail;
    goto fail;
if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
    goto fail;

The flaw with Objective‑C: C is a flawed language. If you know tricks (e.g., switch statements that have default fallthrough behavior), you can pave around it. But Apple cannot rev on C and make it safer; they have to maintain backward compatibility with C.

@implementation NSString (Helper)
- (BOOL)containsString:(NSString *) string {
    NSRange range = [self rangeOfString:string options:NSCaseInsensitiveSearch];
    return range.location != NSNotFound;
}
@end

This containsString category on NSString. In iOS 8, Foundation added a method called containsString:. The one that ships with Foundation is case sensitive, and the one here is case insensitive. With Objective‑C, you are always supposed to prefix your categories with the name of your company; Swift uses namespaces. In general, Swift makes writing code simpler, safer, less buggy, faster. All built into the language. Even if it is just linearly porting Objective‑C to Swift.

What is the Worst Thing That Could Happen? (10:14)

1. Bundling Swift increases size (10:21)

Make sure that you are not bench marking against the bitcode compiled version, but the actual final binary (you have to check some boxes when you are exporting the archive to do it just right).

Thin version: Objective‑C of a Hello World app is 72k vs. Swift, 3.1mb; full version: Objective‑C, 92k vs. 4.6mb. But it is not a major concern (e.g., if you are dealing with a 45mb app, a couple extra mb may not matter). Nevertheless, bear in mind that the cost of downloading is high in emerging markets.

2. New paradigms mean limited support (11:52)

More concerning are the new paradigms, with limited support. Not using a class, moving to struct are the new thing. You may drop in the NSCoding protocol, and get this nice error: non-class type 'Post' cannot conform to class protocol 'NSCoding'. I would recommend if you do decide to jump on Swift, try to timebox these voyages into the perfect world of structs, and do not be afraid to stick to what you already know (maybe you just have to ship).

3. New runtime means new bugs (13:18)

Mike Ash found this bug around weak references. Weak references have a race condition that can cause your app to mysteriously crash. Also, I was shipping something to an internal data build, but the debug build versus the release build was doing something different and crashing on launch.

4. Swift moves fast. Really fast. (14:23)

It is wonderful (for the evolution of the language), but you end up having code churn. Khan Academy has an app with 30,000 lines of code. They spent a week porting code over to the new syntax with Swift 2… A week that you could have been spending delivering valuable functionality to users.

Swift 3.0, as Tyler Fox from Apple admitted, will have breaking changes. Knowing there will be more Swift revs during the year, budget in at least two weeks of time wasted porting Swift syntax and testing for regressions. The cost of moving forward.

Churn Makes for Painful Dependencies (15:17)

As a side effect, when you start bundling Xcode with the version of your language, you get into dependency hell. When Dropbox switched their 2.0 SDK to Swift, people are now having to be tied to the latest version of Xcode. As such, apps enter “maintenance mode.” For instance, last year, I was a technical consultant on a TV show, Silicon Valley, I wrote a small app & ended up getting Swift 1.2 inside the app, and now it is stuck on that version of Xcode. I cannot go back and justify porting this 1.2 version to 2.0 without wasting a week.

Migration has Coordination Costs (17:07)

If you are in a larger company (Facebook, Twitter), teams may be working independently. You need to coordinate with all the satellite teams inside your company. Or often, have two separate teams in your main app (e.g., one team building the fundamental framework & networking stack; then another building the user-facing functionality).

So What’s My Hot Take? (17:56)

If you are in a small team, with low coordination costs, not terrified by burning two weeks having to migrate code, and a last minute bug: go for Swift. If you are already great at Objective‑C, have dependencies, or are busy, wait for Swift 3.0.

With Swift 3.0, they will focus on ABI stability (easier to have different versions of the Swift libraries; it might be shipped with iOS, which will also bring your app size down). With Swift 3.0, it will be interesting to see what they invest with Foundation and UIKit. We can expect updates to the frameworks. We will have more expertise. They will go far off the deep end of writing things in structs. You will find different patterns to replace NSNotificationCenter. By the time Swift 3.0 lands, we will all have the proper expertise.

Thank you! Q&A (20:00)

Q: Is not the plan that Apple is going to phase out Objective‑C at some point? With some of the libraries, recently, they return Swift data types rather than Objective‑C data types. Do you know what the time frame is for that?

Ben: (I do not work at Apple, so I am allowed to just say whatever I want.) There is an interview where they were saying that they love Objective‑C. APIs in OS X Carbon. I think they are still around (although they keep telling developers to stop developing for it). They are deprecated, but they will not remove it. I think that it is always going to be around. They will probably have the exact same APIs until the world is beyond Objective‑C that it does not make sense, and why I think there should be zero pressure about pointing your app for concerns about deprecating the API.

Q: Hopefully things will not break!

Ben: The problem is also so much of iOS. I have heard: Apple’s the type of company that they will build something once, and never touch it again because it works. OS X still has traces of Carbon because it works. If they broke Objective‑C, iOS would probably be the first people to have repercussions. Apple is obsessed about backward compatibility, to the point probably of their detriment with how they maintain backward compatibility with UIKit. I am not worried about Objective‑C breaking.

Q: Is there any practical way to port an Objective‑C app to Swift in chunks, rather than rewriting everything at once?

Ben: I think that is the most beautiful and the most brilliant thing that they have done with Swift: you can go one file at a time. If someone came to me with an app that works perfectly well, a perfect diagram of MVC, I would say: leave that code there and start migrating new work over to Swift, and make sure you drop in the annotations, backport that. If the code works, the important part is coming up with a transition plan. Drop a particular date where you say, “from here on out, unless you have a strong reason not to, you should be writing everything in Swift.”

I have seen situations in different apps where, for instance, a team of developers on this very large team decided that test-unit-style TDD is out, we should be using behavioral driven development. And they started porting over their tests to a BDD framework (but they got distracted and never finished it off). The worst situation is the middle of a transition where new developers start contributing partially to Objective‑C, partially to Swift, and they have no clear direction. It is bad to fragment your resources around your build systems, and in the case of this BDD system, when they started building continuous integration servers, all the ops people had to build two separate servers that parsed two different reports, and you end up spending twice as much effort. It is more important to have a transition plan and say, from this point forward we are just doing Swift, and not necessarily go back and waste time in seeking purity.

Q: I have been working on a project that has a large Objective‑C code base, and it is not feeling it is time to go Swift yet. But one thing I have started doing is when I create new classes, I am making sure that for all my pointers I am using the nonnull and nullable keywords. Does that seem like a good strategy to position oneself for going Swift eventually?

Ben: Definitely, that is future-proofing it, as much as your code starts looking like C++. If I am a one-person team, working on the app myself, and I have full control over the day I abandon the old code, I might be lazy. But if you are looking toward the future, then I would drop in the annotations today.

Q: When you mentioned transition plans, plotting forward, and moving from Objective‑C to Swift, are there other transitions that look or feel similar to this transition? Ones where you have seen either teams, or applications, or entire organizations, that have made that transition successfully? Are there other examples we can look at from the last 35 years of software development. This is not the first time this has happened. Who has done this well and who has not?

Ben: It might be before my time, but I guess moving over to OS X from Carbon would be one example. More recently, the transition from manual reference counting to automatic reference counting. I would have waited longer to move over to automatic reference counting, but there was a strong proponent in our group who said, “We used it when we were at Apple, and it reduced crashes.” It was for one particular engineer who went back and changed the ownership model (a couple of weeks of being holed-up in a room, and slowly dribbling in the patches). That was a pretty smooth transition because we took it from a piece by piece approach, and there was a pragmatic element of this particular ownership pattern is bonkers, we are going to leave this file manual reference counting rather than waste a week making perfect the enemy of the good.

Unfortunately, the closest I can think of is when engineers went down paths of choosing a particular framework on iOS, that wasn’t one of Apple’s, and they do rewrite from scratch. Very painful. I would say it is better to take a measured approach, piece by piece, and do not fall for the temptation. If you are tempted by doing a full rewrite, it tends to be not the language, but the patterns, MVC, or deeper structural issues of the company. I have observed at least one rewrite before iOS development that happened where we holed-up our best developers in a room for months, and they rewrote the app. As soon as they started adding more developers, and the same lack of code review, and the same issues, it was steering back to the same problems to begin with.

Q: About developing a new app: Would you go directly to Swift? Brand new app, starting from scratch.

Ben: If I were working on something where it was just me: Swift! It is great, and if it becomes big, by the time Swift 3.0 is starting to come along, I would sell it for a billion dollars to Facebook. I was talking someone for whom an SDK was a major part of their strategy, and they felt that all the headaches are not worth it. As soon as you start involving the responsibility to your company and investors, I tend to be conservative; I want to make it as simple and painfree for everyone else, when they are putting money in my company.

Q: There was a problem with Swift and NSNotification?

Ben: Yes. NSNotificationCenter requires NSObject or reference types: you cannot drop a Swift value type. Not that notifications are a good API, but it has its value. If I dropped NSNotificationCenter, I would have to come up with a new way to do the same thing. I would say that it is more of a distraction. Do we want to structure our notifications, e.g. having a registration center, an alternative to NSNotificationCenter? As you start charting into territory that you are not familiar with. Take something that is slightly less efficient but I can do without thinking because I know this particular pattern works 10 times out of 10, then to start veering into, this particular piece does not work… This has a ripple effect, and I start having to reinvent stuff that should be rote for me.

Q: You just came up with an idea for a new product and company: an alternative notifications center. You will be the next Realm..

Ben: Exactly.

Next Up: Build a Realtime Swift App with Realm #1: Building Reactive Apps with Realm

General link arrow white

About the content

This content has been published here with the express permission of the author.

Ben Sandofsky

Ben Sandofsky builds apps, advises startups, and teaches with CodePath. He has shipped software for over a decade, from tiny startups to giant enterprise companies. He spent over four years at Twitter; among other projects, he was tech lead for Twitter for iPhone, iPad, and Mac. Last year he was a technical consultant for HBO’s Silicon Valley.

4 design patterns for a RESTless mobile integration »

close