[swift-users] object.self?

Rick Mann rmann at latencyzero.com
Fri Jul 8 11:38:01 CDT 2016


I just saw a question which brought up something I didn't know about. Apparently sometimes you have to call object.self in a place that looks like you should just use "object." What does this usage mean?

for subclassObject in objects {
    switch subclassObject.self {	<--- Here, why not "subclassObject" alone?
    case is Subclass1:
        doSomethingWith(subclassObject as! Subclass1)

    case is Subclass2:
        doSomethingWith(subclassObject as! Subclass2)

    case is Subclass3:
        doSomethingWith(subclassObject as! Subclass3)

    default:
        break
    }
}

Thanks,
Rick

> On Jul 8, 2016, at 08:15 , Dan Loewenherz via swift-users <swift-users at swift.org> wrote:
> 
> 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
> 
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users


-- 
Rick Mann
rmann at latencyzero.com




More information about the swift-users mailing list