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.

In dealing with code that can fail, you have three options:

  1. Ignore the error using the try? keyword, thereby unifying the optional type system with Swift 2’s error handling model. The use of try? ensures that all errors (if thrown) are consumed and an optional value is returned as a right-hand value.
  2. Handle any errors that are thrown from unsafe code using the do/catch statements.
  3. Propagate errors by adding the throws keyword to the method or function signature. Unlike Java, errors do not propagate by default.

Error handling in Swift 2 improves on the Objective-C error model -- which relies on documentation and comments. Swift 2’s error-handling model provides safety through compile-time checks that prevent unsafe code from entering your code base.

For example, you can leverage error handling in code that validates a customer has typed in an authentic name and email address:

// Create a custom error type by conforming to the ErrorType protocol
enum ValidationError: ErrorType {
   case InvalidName
   case InvalidEmail
   case InvalidAge(age: Int)
}
// Check name against your name policies
func validateName(name: String) throws {
   // Use guard statements to prevent invalid user input
   guard name.characters.count > 0 else {
       throwValidationError.InvalidName
   }
}
// Process a new customer using required attributes
func onboardNewCustomer(name: String, email: String, age: Int) {
   do {
       print("Started onboarding")
       // You must use the try keyword for any method that can throw an error
       try validateName(name)     
       // Exercise: Validate other required attributes (age, email, etc.)     
       // Finished processing if no errors
       print("Finished onboarding")
   } catch let error as ValidationError {
       // Using a local variable you can catch all ValidationErrors     
       // The local error variable can be handled with a switch
       switch(error) {
       case ValidationError.InvalidName:
           print("Invalid name!")
       case ValidationError.InvalidEmail:
           print("Invalid birthday!")
       case ValidationError.InvalidAge(let age):
           print("Invalid age \(age)!")
       }
   }
   catch {   // default error catch
       print("Catch errors here:", error) // error is default name
   }
}
onboardNewCustomer("", email: "", age: 12223) // Invalid!
onboardNewCustomer("paul", email: "PaulSolt@iPhoneDev.tv", age: 29)
Download Swift Playground files

The new error handling model works well with the new defer keyword in recovering and running additional lines of code if there is an error thrown in your codebase. This is similar to Java’s finally keyword.

protocol extensions

Apple’s v1.0 release of Swift came with some quirks, like the plethora of global free-standing functions that were poorly documented and hard to find within the Swift Standard Library. Developers who rely on code completion to code faster (myself included) had trouble figuring out how to write code after years of experience with Objective-C.

 

Previous Page  1  2  3  4  5  6  7  Next Page 

Sign up for CIO Asia eNewsletters.