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
// Inner scope (new x variable masks outer scope x variable)
let x = 10
// Inner inner scope ... inception
let x = 200
print("x:", x) // x: 200
print("x:", x) // x: 10
// outer scope
print("x:", x) // x: 7
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.
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
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.
Sign up for CIO Asia eNewsletters.