[swift-users] Multiple value-binding patterns in a single switch case

Glen Huang heyhgl at gmail.com
Fri Jun 9 05:34:05 CDT 2017


Hi, I wonder what's the correct way to express something like this in swift:

Say I have a superclass with two subclasses:

class Animal {}
class Dog: Animal {
    let name = "Dog"
}
class Cat: Animal {
    var name: String {
        return "Cat"
    }
}

And I want to display the name with a switch:

switch animal {
case let a as Dog, let a as Cat:
    label.text = a.name
default:
    break
}

Swift currently won't allow me to use multiple value-binding patterns like this. I wonder what's the right way to express it? Must I repeat the statements?

switch animal {
case let a as Dog:
    label.text = a.name
case let a as Cat:
    label.text = a.name
default:
    break
}

I also tried fallthrough, but swift won't let me fall through to a value-binding pattern:

switch animal {
case let a as Dog:
    fallthrough // error
case let a as Cat:
    label.text = a.name
default:
    break
}

I'm at my wits end. Could someone shed some light on this? Thanks.


More information about the swift-users mailing list