Swift 2.1: Printable errors

Here’s a Swift 2.1 snippet demonstrating how you can print/show error messages based on the thrown error type.

Basically we are implementing the CustomStringConvertible protocol, which allows us to provide a human readable error message for each enum case.

enum StrError: ErrorType, CustomStringConvertible {
  case StrIsEmpty

  var description:String {
    switch self {
      case .StrIsEmpty:
        return "The provided string is empty"

func showString(input: String) throws {
    guard !str.isEmpty else {
        throw StrError.StrIsEmpty
    print("string: \(input)")

do {
    try showString("")
} catch let error as StrError {
    print("Error: \(error)")

Leave a Reply

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