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.

Seven Swift 2 enhancements every iOS developer will love

When Apple introduced Swift in June 2014, the initial fanfare centered on the brand-new language’s emphasis on performance, approachability, and ease. Now, with Swift 2 out more than a year later, Apple has made good on that emphasis, pushing Swift closer to the kind of readability and maintainability development shops and IT organizations expect of a mature language.

Many of the enhancements to Swift, through both the Swift 2.0 update and subsequent Swift 2.1 update, have made the language more explicit and intentional, and in turns, Swift 2 code will be safer and easier to maintain for years to come (especially now that Swift is open source). New language constructs (keywords) in Swift 2 improve the readability of control flow -- the order in which lines of code are executed. Thanks to these new keywords, collaborating on Swift code will be much more productive and efficient.

Apple has also enhanced Xcode 7 with new features and modernized its SDKs across OS X 10.11, iOS 9, and watchOS 2. The API overhaul even includes new features for Objective-C, including lightweight generics and OptionSetType, which makes Objective-C APIs Swift-like when invoked from Swift code.

Easy-to-follow code is a vital concern for development teams, especially in business contexts, as “witty” or complex code reduces maintainability, introduces and hides serious bugs, and can lead to security leaks. Here are seven new features available with Swift 2 that will help you and your team collaborate more effectively on a more efficient, secure code base.

guard keyword

Swift 2’s new guard keyword provides precondition checking in a method -- exactly like you might find with an if/else statement in Objective-C.

There are two wins here:

Firstly, the guard keyword makes it clear that you, as the programmer, are asserting that certain preconditions must be met before executing the code that follows.

Secondly, the guard keyword makes the control flow easier to read. Instead of injecting a gigantic if/else structure with no clear beginning or end, all of the assertion and cleanup code is compacted into one location.

This makes early exits from Swift methods and functions easy for fellow programmers to follow and explicitly clear -- a win for code maintainability.

Code that follows a guard statement can safely assume all of the parameters required to perform an action are ready to use:

// A value type struct to store data (passed by value i.e. copied!)
struct EmailSubscriber {
   var firstName: String
   var email: String
}
// A supporting function that illustrates valid/invalid values
func validateEmail(email: String) -> Bool {
   return true// false // Implementation as a reader exercise
}
// Create a new subscriber if the parameters meet the requirements
func createEmailSubscriber(firstName: String, email: String) -> EmailSubscriber? {
   // Prevent empty text input from the user
   guard firstName.characters.count > 0 else {
       print("Invalid First Name")
       return nil
   }
   // Assert it's an accepted email format: i.e. PaulSolt@iPhoneDev.tv
    guard validateEmail(email) else {
       print("Email Format Error: Invalid Email")
       return nil
   }
   // Any code path that reaches this point has been validated
   return EmailSubscriber(firstName: firstName, email: email)
}
// Missing data results in a nil value
let invalid = createEmailSubscriber("", email: "PaulSolt@iPhoneDev.tv")
print("Subscriber is invalid, returned: ", invalid)
// Attempts to force unwrap and use nil values causes crashes!
// Tip: Use the if/let syntax to work safely with optional types
//print("Subscriber is invalid, returned: ", invalid!.firstName) // ERROR!
// Complete data results in a new digital subscriber value/object
let valid = createEmailSubscriber("Paul", email: "PaulSolt@iPhoneDev.tv")
print(valid!.firstName, "'s email is: \(valid!.email)")
Download Swift Playground files

 

1  2  3  4  5  6  7  Next Page 

Sign up for CIO Asia eNewsletters.