简体   繁体   中英

Determining the type of Swift class

I am trying to determine the class of an object in a class hierarchy. I am at lost to explain why the test in the example below fails.

    class BasicLocation {}
        class AddressLocation : BasicLocation {}
        class ContactLocation : BasicLocation {}

        func mapView(_ mapView : MKMapView, viewFor: MKAnnotation)
        ->MKAnnotationView?{
        if let test = viewFor as? BasicLocation {
            let basicType = BasicLocation()
            let a = type(of:test)
            let b = type(of:basicType)
            let c = type(of:test)
            NSLog("a=\(a), type of a=\(type(of:a))")
            NSLog("b=\(b), type of b=\(type(of:b))")
            NSLog("c=\(c), type of b=\(type(of:c))")
            if a == b {
                NSLog("passed a and b")
            } else {
               NSLog("a and b do not match match")
            }
            if a == c {
                NSLog("passed a and c")
            }

output

>a=BasicLocation, type of a=BasicLocation.Type  
>b=BasicLocation, type of b=BasicLocation.Type  
>c=BasicLocation, type of b=BasicLocation.Type  
>a and b do not match match  
>a and c natch

Once you have said

if let test = viewFor as? BasicLocation

...If that test passes, stop. You now know that test is a BasicLocation instance, or we wouldn't have passed the test.

Everything else you're doing is just silly. Equality comparison between metatypes is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM