Binding child property in switch case

Is there another way of writing the following switch case statement without using an implicitly-unwrapped optional?

switch action {
    // ...
    case let action as LoadDidSucceed where action.model is Self:
        self = action.model as! Self
    // ...
}

I feel like I must be missing a more concise syntax. Can I bind action.model as Self right in the case statement somehow?

1 Like

It would be a lot easier for me to help you if you posted the type of action and Self. Also, your code currently isn't using an implicitly unwrapped optional.

You could use an if statement:

if let loadDidSucceed = action as? LoadDidSucceed, let model = loadDidSucceed.model as? Self {
    self = model
}
4 Likes

The problem is that you're switching on a parent of what you actually want to bind to. switch doesn't have a direct facility for that. Instead, you need to move logic into a case as soon as you've matched the outer pattern.

    case let action as LoadDidSucceed:
      guard let model = action.model as? Self else { fallthrough }
      self = model
2 Likes

What does "parent" mean in this context?

An ancestor of the desired variable to be bound, which does not provide access to it via an associated value.

I think you could write an enum to get around this, which would pattern match accordingly. It sounds convoluted but maybe it's actually great.

I don't know what the "ancestor" of a variable is. Please provide an example.

Thanks both. I think you’re right @Jessy, there isn’t a way to de-structure action inline and bind directly to the child property like you can with an enum, so there isn’t any way to make this any more concise. Here’s some more context:

protocol Action {}
protocol Model {}

struct LoadDidSucceed: Action {
    let model: Model
}

struct MyModel: Model {
    mutating func update(action: Action) {
        switch action {
            case let action as LoadDidSucceed where action.model is Self:
                self = action.model as! Self

            default:
                ()
        }
    }
}
Terms of Service

Privacy Policy

Cookie Policy