[swift-users] Multiple value-binding patterns in a single switch case
Jens Persson
jens at bitcycle.com
Fri Jun 9 06:28:31 CDT 2017
I'm not sure what you are trying to achieve.
Why can't you just do:
label.text = animal.nam
?
Is it because not all Animals have names?
If so, you could perhaps use something like this:
class Animal {}
protocol Named {
var name: String { get }
}
class Dog: Animal, Named {
let name = "Dog"
}
class Cat: Animal, Named {
var name: String {
return "Cat"
}
}
let animals: [Animal] = [Cat(), Dog()]
for animal in animals {
if let namedAnimal = animal as? Named {
print(namedAnimal.name)
}
}
On Fri, Jun 9, 2017 at 12:34 PM, Glen Huang via swift-users <
swift-users at swift.org> wrote:
> 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.
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170609/a3e01def/attachment.html>
More information about the swift-users
mailing list