[swift-users] Switch based on let

Dan Loewenherz dan at lionheartsw.com
Fri Jul 8 10:15:48 CDT 2016


To my knowledge, you can’t do exactly what you’re trying to do, but this is
close:

for subclassObject in objects {

    switch subclassObject.self {

    case is Subclass1:

        doSomethingWith(subclassObject as! Subclass1)


    case is Subclass2:

        doSomethingWith(subclassObject as! Subclass2)


    case is Subclass3:

        doSomethingWith(subclassObject as! Subclass3)


    default:

        break

    }

}

On Fri, Jul 8, 2016 at 10:11 AM, Nate Birkholz via swift-users <
swift-users at swift.org> wrote:

> This looks like it doesn't work (swift 2.x), but wanted to be sure it's
> not supported:
>
> class Superclass {}
> class Subclass1 : Superclass {}
> class Subclass2 : Superclass {}
> class Subclass3 : Superclass {}
>
> let sc1 = Subclass1()
> let sc2 = Subclass2()
> let sc3 = Subclass3()
>
> let objects : [Superclass] = [sc1, sc2, sc3]
>
> for subclassObject in objects {
>     switch subclassObject {
>     case let object = subclassObject as? Subclass1:
>         doSomethingWith(object)
>     case let object = subclassObject as? Subclass2:
>         doSomethingWith(object)
>     case let object = subclassObject as? Subclass3:
>         doSomethingWith(object)
>     default:
>         return
>     }
> }
> This gives an error, expecting a colon (:) after object on every case.
>
> I wanted to be sure I wasn't missing something in my syntax (nor some
> obvious-to-others reason this isn't supported) before going to swift
> evolution.
>
>
> --
> Nate Birkholz
>
> _______________________________________________
> 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/20160708/2660bdc1/attachment.html>


More information about the swift-users mailing list