Cool New Stuff in Swift 2

At WWDC 2015 we found out that Apple wasn’t kidding about Swift. Introduced just a year before at WWDC 2014 a year later it was difficult to find any Objective-C slides in any of the sessions and it was clear Apple doubled-down on Swift and it is the future of Apple software development. The cherry on top was Open Sourcing it.

If you have been following along then you know Swift and Xcode have been somewhat of a moving incremental target evolving from 1.0 to 1.1 to 1.2 and now 2.0 in just under a year. Because of these incremental bumps I thought I would highlight a checklist of seven magnificent things composed of what I think are some of the cool new things you’ll find in your Swift 2 journeys as Swift enters year two.

1. Goodbye println
To warm things up we’ll start with an easy but obvious change – println() is gone. This is now print().
If you have these in any old Swift 1.x code then it should be easy enough to update.

Why the change? Streamlining, maybe. In any case if you really want to keep println() you could implement your own global function in front of Swift’s print – although at first this may sound silly this could be a good pattern for logging where you comment out the print in the body of your function or make it automatic by using a conditional:

        func println(object: Any) {
#if DEBUG
Swift.print(object)
#endif
}

 

2. Protocol Extensions
Extensions are Swift’s answer to Objective-C Categories on steroids allowing you to not only add functionality to existing classes but structures, enumeration (all in Swift 1.x) and now protocols.

This may seem like no big deal at first but this introduces a new, transformative bionic style of programming called Protocol-Oriented Programming which opens up the potential for new patterns in your code.

The Apple Swift team is dogfooding this new feature in a big way by using it all over the Swift standard library making the API more discoverable and readable.

An example would be the finding of an item in an array which is a homage to JavaScript with the array.indexOf(“) instead of the awkward find(array, “string”) function. Use the dot to discover these functions on an object. Thank you protocol extensions.

Speaking of arrays and JavaScript not sure why Apple just doesn’t use string.length instead of flip-flopping every release from 1.0’s countElements(string) to 1.2’s count(string) to now 2.0’s string.characters.count to get the length of the string. Maybe a protocol extension would help here.

 

3. #available
Targeting multiple iOS versions and want to use a simple way to determine whether an API is available in the current version. Now we have #available to help us check API availability.
        if #available(iOS 9.0, *) {
// do this great new iOS 9 feature
} else { // fall back on the iOS 7 or 8 way to do it
// do this other thing
}

Isn’t that just #Awesome!

4. I like your new do
So do { } while is gone – well, technically only the do is gone – change it to repeat { } while.

But why would Apple change that you ask? Well, the team realized they needed do for something else. What you ask? The new do { } catch syntax which makes error handling much leaner.

        do {
// do your thing
} catch {
// yikes! - something went wrong
}

This is great not just for handling Apple errors but also you can throw and handle your own custom errors by using the throws keyword to throw your own error which you can catch and handle gracefully in one place including the passing of messages.

For more visit the Error Handling section in the Swift Guide.

 

5. The Changing of the Guard
In ObjC you would make sure a value exists and meets a condition usually by checking for values that you don’t want (if nameFound != nil) which makes your code confusing and then in Swift using Optional Binding (if let name = foundName where foundName != nil).

Helping you make your intent clearer and unwrapping optionals automatically comes the new defensive design inspired guard keyword.

Guard eliminates this by having you do the checks you do want first and exiting if they aren’t met. Some call this the bouncer pattern since its like a bouncer at a club checking for ID or desirability before letting you in.

        guard let name = foundName else {
// value requirement not met - return
}
// all good - proceed with name - thank you bouncer
}

For more you can read up on Branching Statements in the Swift Programming Language Guide.

 

6. Lets defer that
Sometimes you need to do something before you exit a function. As the code matures you have various exit points to the function and need to do that thing in more than one place. In the best case you are violating DRY and repeating yourself and in the worst case you actually exit without doing that thing like say closing a stream (say you didn’t repeat yourself in the guard).  That’s where defer comes to the rescue as the procrastinator’s ultimate tool.

Now you can simply add a defer clause to the top of your function

        defer {
// do that thing
}

and when the function exits its scope the defer statement is called – good things come to those who wait.

7. Xcode 7 Better Warnings
Finally, no Swift conversation would be complete without a mention of Xcode and one thing I found cool is that now Xcode warns you when you are using vars that you never mutate letting you know that you should probably treat them as constants and use a let. Nice to see compiler optimizations coming through like this.

 

Where to next?

These have been the magnificent seven cool things I’ve found since Xcode 7 and Swift 2 went live.

But they are just the tip of the iceberg of a colossal release.

Be sure to check out the Swift Blog – specifically, the Swift 2.0 Announcement.

Also, grab your popcorn and check out Chris Lattner present the WWDC 2015 What’s New in Swift 2 session.

Now go off and add your own cool Swift 2 stuff to your next killer Swift app.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s