Subscribe / Unsubscribe Enewsletters | Login | Register

Pencil Banner

Seven Swift 2 enhancements every iOS developer will love

Paul Solt | Feb. 2, 2016
Apple makes good on Swift’s emphasis on performance, approachability, and ease in latest update.

The do keyword has been repurposed to create new scope, unlike every other popular language that uses it for loops. Now, when you want to create an inner scope inside an existing scope, you use do. This is important when you need to deallocate expensive resources in a tight loop or if you want to help ARC (Automatic Reference Counting) effectively clean up expensive resources:

// Outer scope
let x = 7
do {
   // Inner scope (new x variable masks outer scope x variable)
   let x = 10 
   do {
       // Inner inner scope ... inception
       let x = 200
       print("x:", x) // x: 200
   } 
   print("x:", x) // x: 10
}
// outer scope
print("x:", x) // x: 7
Download Swift Playground files

As with C++ or Objective-C, you can nest do scopes to enhance your local variable lifetime control.

Where is this useful? If you process 15-megapixel images or large data files sequentially in a tight loop, you can run out of memory, which will cause iOS to force quit your app. There’s a hard memory footprint limit on iOS -- once you pass it, your app “crashes” and you have an unhappy customer. Using the new do scope, you can avoid the crash and deallocate memory (using ARC) after each filter pass, instead of at the end of a tight loop.

These new and repurposed Swift keywords play perfectly with the new error handling model in Swift 2.

error handling

Swift 2’s new error handling is one of the pillars of the improved language. It provides a feature that has been missing from Swift and is expensive (performance-wise) to use in Objective-C.

Error handling in Swift creates an implicit control flow structure for dealing with unexpected issues from networking, input, and data. Swift uses the new do keyword for scoping the traditional try/catch structure popular in Java. In Swift, you use do/catch blocks.

Swift 2’s error handling isn’t a cure-all. Instead, it’s designed to help you deal with recoverable issues, such as invalid input from user forms or invalid (or unexpected) response data from a Web server. Error handling can also be used to handle file I/O issues, networking availability, and other common problems associated with poor cellphone reception and limited disk storage on mobile phones.

Error handling is built into the method signature using the throws keyword. With native language support for error propagation, the additional NSError pointer parameter is dropped from all APIs because it is redundant.

Every line of code that can fail (unsafe code) must be marked with the new try keyword. This makes it easier for everyone working on the code to quickly know that a particular line of code could fail.

 

Previous Page  1  2  3  4  5  6  7  Next Page 

Sign up for CIO Asia eNewsletters.