Using if case let to match specific enum case
When working with enum and need to get associated value from one case, instead of switching and handle all the cases, we can use if case let
keyword.
For example if we have enum like this:
import Foundation
enum Message {
case text(userId: String, date: Date)
case draft(userId: String, date: Date)
case join(userId: String, date: Date)
case leave(userId: String, date: Date)
case balloon(userId: String, date: Date)
}
then we want to log userId
when user send balloon message, we can use if case let
if case let Message.balloon(userId, date) = textMessage {
log(userId)
}
Linked Notes:
Pattern matching in Enum
While working using [[The Composable Architecture]] I often need to match a specific enum action or dealing with extracting associated value in enum. There’s a few different way to pattern matching an enum and extract its associated value:
Today I learn
I believe that we can learn something new everyday, that’s why I set this page to record what I learn during the day.