iOS Error Handling in Swift Error Handling Handling Errors

Ken Gerlinger
Ken Gerlinger
2,898 Points

I don't understand why we have "let descprition" inside the parentheses

what does the constant inside the parentheses mean ?

catch FriendError.invalidData(let description) {

2 Answers

Jhoan Arango
MOD
Jhoan Arango
Treehouse Moderator 12,136 Points

Hello Ken,

Enums have associated values, that you can "extract" their value by creating a constant.

For example,

Consider the following Enum

// An enum that can store associated values 

enum WeekDays {
    case monday(String)
    case tuesday(String)
    case wednesday(String)
    case thursday(String)
    case friday(String)
}

We can now create an instance of the WeekDays enum with an associated value.

let weekDay = WeekDays.monday("Not my favorite day") // Assigning a value to its associated value

Now we can use a switch statement to "switch" through it, and extract the value by initializing a constant.

switch weekDay {
case .monday(let value) : // Extracting the value by initializing a constant
    print(value) // Prints : Not my favorite day
case .tuesday(let value) :
    print(value)
default:
    break
}

// Or you can also do it this way

switch weekDay {
case let .monday(value)  :
    print(value)
case let .tuesday(value) :
    print(value)
default:
    break
}

This is essentially what Pasan is doing in his video with the Error handling. Notice how he uses an enum to define errors, and these errors have an associated value, then he is extracting it's value if the error is thrown.

For more information about this you should look at Enums and associated values.

Click here to see more about enums.

Hope this helps

missgeekbunny
missgeekbunny
37,030 Points

You are initializing the description constant in the catch statement so that it actually has anything from the error. Otherwise it wouldn't be useable in the function cause once the error is cause you don't know anything about it but what you bind from the enum.