<div dir="ltr">I'm not sure what you are trying to achieve.<div>Why can't you just do:</div><div>label.text = animal.nam</div><div>?</div><div>Is it because not all Animals have names?</div><div>If so, you could perhaps use something like this:<br></div><div><br></div><div><div>class Animal {}</div><div>protocol Named {</div><div> var name: String { get }</div><div>}</div><div>class Dog: Animal, Named {</div><div> let name = "Dog"</div><div>}</div><div>class Cat: Animal, Named {</div><div> var name: String {</div><div> return "Cat"</div><div> }</div><div>}</div><div><br></div><div>let animals: [Animal] = [Cat(), Dog()]</div><div><br></div><div>for animal in animals {</div><div> if let namedAnimal = animal as? Named {</div><div> print(namedAnimal.name)</div><div> }</div><div>}</div></div><div><br></div><div><br></div><div><br></div></div><div class="gmail_extra"><br><div class="gmail_quote">On Fri, Jun 9, 2017 at 12:34 PM, Glen Huang via swift-users <span dir="ltr"><<a href="mailto:swift-users@swift.org" target="_blank">swift-users@swift.org</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Hi, I wonder what's the correct way to express something like this in swift:<br>
<br>
Say I have a superclass with two subclasses:<br>
<br>
class Animal {}<br>
class Dog: Animal {<br>
let name = "Dog"<br>
}<br>
class Cat: Animal {<br>
var name: String {<br>
return "Cat"<br>
}<br>
}<br>
<br>
And I want to display the name with a switch:<br>
<br>
switch animal {<br>
case let a as Dog, let a as Cat:<br>
label.text = <a href="http://a.name" rel="noreferrer" target="_blank">a.name</a><br>
default:<br>
break<br>
}<br>
<br>
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?<br>
<br>
switch animal {<br>
case let a as Dog:<br>
label.text = <a href="http://a.name" rel="noreferrer" target="_blank">a.name</a><br>
case let a as Cat:<br>
label.text = <a href="http://a.name" rel="noreferrer" target="_blank">a.name</a><br>
default:<br>
break<br>
}<br>
<br>
I also tried fallthrough, but swift won't let me fall through to a value-binding pattern:<br>
<br>
switch animal {<br>
case let a as Dog:<br>
fallthrough // error<br>
case let a as Cat:<br>
label.text = <a href="http://a.name" rel="noreferrer" target="_blank">a.name</a><br>
default:<br>
break<br>
}<br>
<br>
I'm at my wits end. Could someone shed some light on this? Thanks.<br>
______________________________<wbr>_________________<br>
swift-users mailing list<br>
<a href="mailto:swift-users@swift.org">swift-users@swift.org</a><br>
<a href="https://lists.swift.org/mailman/listinfo/swift-users" rel="noreferrer" target="_blank">https://lists.swift.org/<wbr>mailman/listinfo/swift-users</a><br>
</blockquote></div><br></div>