What's new in Swift 2.0
In this section, we will take a look at some of the new features that come as part of the Swift 2.0 programming language.
Error handling
Error handling is defined as the process of responding to and recovering from error conditions within your program. The Swift language provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime. In Swift, these are referred to as throwing functions and throwing methods.
In Swift 2.0, error handling has vastly improved and adds an additional layer of safety to error checking. You can use the throws
keyword to specify which functions and method are most likely to cause an error. You can implement and use the do
, try
, and catch
keywords to handle something that could likely throw an error.
Let's take a look at a code example to see how we can put this into practice.
Clear the contents of the playground template and replace them with the following code snippet:
/*: # Swift Language Basics - What's new in Swift 2.0 : Created by Steven F. Daniel : Copyright © 2015 GENIESOFT STUDIOS. All Rights Reserved. */ import Foundation enum EncryptionError: ErrorType { case Empty case Short } // Method to handle the Encryption func encryptString(str: String, withPassword password: String) throws -> String { if password.characters.count > 0 { // Password is valid } else { throw EncryptionError.Empty } if password.characters.count >= 5 { // Password is valid } else { throw EncryptionError.Short } // Begin constructing our encrypted string let encrypted = password + str + password return String(encrypted.characters.reverse()) } // Call our method to encrypt our string do { let encrypted = try encryptString("Encrypted String Goes Here", withPassword: "123") print(encrypted) } catch EncryptionError.Empty { print("You must provide a password.") } catch EncryptionError.Short { print("Passwords must be at least five characters.") } catch { print("An error occurred!") }
Take a look at the following screenshot now:
As you can see in the preceding code, we began by creating an enum
object that derives from the ErrorType
class so that we could create and throw an error. Next, we created a method called encryptString
that takes two parameters: str
and password
. This method performed a check to ensure that we didn't pass an empty password.
If our method determines that we did not specify a valid password, we will automatically throw an error using EncryptionError.Empty
and exit from this method. Alternatively, if we provide a valid password and string to encrypt, our string will be encrypted.
Binding
Binding in Swift is something new and provides a means of checking whether a variable contains a valid value prior to continuing and exiting from the method otherwise. Fortunately, Swift 2.0 provides you with exactly this, and it is called the guard
keyword.
Let's go back to our previous code snippet and take a look at how we can implement the guard
statement to our conditional checking within our encryptedString
method.
Modify the contents of the playground template and replace them with the following highlighted sections:
// Method to handle the Encryption func encryptString(str: String, withPassword password: String) throws -> String { guard password.characters.count > 0 else { throw EncryptionError.Empty } guard password.characters.count >= 5 else { throw EncryptionError.Short } // Begin constructing our encrypted string let encrypted = password + str + password return String(encrypted.characters.reverse()) }
As you can see in the preceding code snippet, using the guard
keyword, you can provide a code block to perform a conditional check within the else
statement that will run if the condition fails. This will make your code cleaner as the guard
statement lets you trap invalid parameters from being passed to a method. Any conditions you would have checked using if
before you can now check using guard
.
Protocol extensions
In Swift 2.0, you have the ability to extend protocols and add additional implementations for properties and methods. For example, you can choose to add additional methods to the String
or Array
classes, as follows:
/* # What's new in Swift 2.0 - Protocol Extensions The first content line displayed in this block of rich text. */ import Foundation let greeting = "Working with Swift Rocks!" // Extend the String class to include additional methods extension CustomStringConvertible { var uCaseString: String { return "\(self.description.uppercaseString)!!!" } } print(greeting.uCaseString)
Take a look at the following screenshot now:
As you can see in the preceding code, we extended the String
class using the CustomStringConvertible
protocol, which most of the Foundation
class objects conform to. Using protocol extensions, they provide you with a wide variety of ways to extend the base classes so that you can add and implement your very own custom functionalities.