Reader small image

You're reading from  Apple Watch App Development

Product typeBook
Published inApr 2016
Reading LevelIntermediate
Publisher
ISBN-139781785886362
Edition1st Edition
Languages
Right arrow
Author (1)
Steven F. Daniel
Steven F. Daniel
author image
Steven F. Daniel

Steven F. Daniel is the CEO and founder of GENIESOFT STUDIOS, a software development company based in Melbourne, Victoria, that focuses primarily on developing games and business applications for the iOS, Android, and Mac OS X platforms. He is an experienced software engineer with more than 17 years' experience and is extremely passionate about making people employable by helping them use their existing skills in iOS, Android, and Xamarin to get the job done. He is a member of the SQL Server Special Interest Group (SQLSIG), CocoaHeads, and the Java Community. He was the co-founder and Chief Technology Officer (CTO) at SoftMpire Pty Ltd., a company focused primarily on developing business applications for the iOS and Android platforms.
Read more about Steven F. Daniel

Right arrow

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.

Previous PageNext Page
You have been reading a chapter from
Apple Watch App Development
Published in: Apr 2016Publisher: ISBN-13: 9781785886362
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Steven F. Daniel

Steven F. Daniel is the CEO and founder of GENIESOFT STUDIOS, a software development company based in Melbourne, Victoria, that focuses primarily on developing games and business applications for the iOS, Android, and Mac OS X platforms. He is an experienced software engineer with more than 17 years' experience and is extremely passionate about making people employable by helping them use their existing skills in iOS, Android, and Xamarin to get the job done. He is a member of the SQL Server Special Interest Group (SQLSIG), CocoaHeads, and the Java Community. He was the co-founder and Chief Technology Officer (CTO) at SoftMpire Pty Ltd., a company focused primarily on developing business applications for the iOS and Android platforms.
Read more about Steven F. Daniel