Throw a Message Along with an ErrorType in Swift 2.2

Paul Hudson posted a very helpful article on Error handling in Swift 2: try, catch, do and throw.  One thing he mentioned, but didn’t complete the code on was throwing a message along with an ErrorType in Swift 2.2.

Here is the completed example.

enum EncryptionError: ErrorType {
  case Empty
  case Short
  case Obvious(String)
}

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 }
  guard password != "12345" else { throw EncryptionError.Obvious("Password 12345 is too obvious.") }
  
  let encrypted = password + str + password
  return String(encrypted.characters.reverse())
}

do {
  let encrypted = try encryptString("secret information!", withPassword: "12345")
  
} catch EncryptionError.Empty {
  print("You must provide a password.")
  
} catch EncryptionError.Short {
  print("Passwords must be at least five characters, preferably eight or more.")
  
} catch EncryptionError.Obvious(let errorMessage) {
  print(errorMessage)
  
} catch {
  print("Something went wrong!")
}

Notice the enumeration case Obvious(String). Method encryptString(_:withPassword) sets up a guard statement for this case as follows:
guard password != "12345" else { throw EncryptionError.Obvious("Password 12345 is too obvious.") }

The article stopped short of showing how to catch the message, “Password 12345 is too obvious.”, along with the ErrorType. This can be done by assigning a constant to the String as shown here.

catch EncryptionError.Obvious(let errorMessage)

For more details on using the Swift language, check out Ray Wenderlich’s Beginning Swift Bundle.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *