0

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
Stephen
  • 101
  • 5
  • what is viewFor here? We can't see the code that set it up so we have no idea how it affects the output. – Jeremy Gurr Dec 13 '16 at 15:59
  • what is `test`? – holex Dec 13 '16 at 16:21
  • This might be handy to know: http://stackoverflow.com/a/40388434/3141234 – Alexander Dec 13 '16 at 17:02
  • In the code as written, `viewFor as? BasicLocation` should always fail. `BasicLocation` does not implement `MKAnnotation`. If it does implement `MKAnnotation`, then it implements `NSObjectProtocol`, and that completely changes this question. NSObject subclasses permit introspection that arbitrary Swift subclasses do not. See `.isMember(of:)` if this is an NSObject. – Rob Napier Dec 13 '16 at 20:54

1 Answers1

0

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • The first test determines only that the class is a member of the hierarchy. At issue is which class in the hierarchy. – Stephen Dec 13 '16 at 20:41
  • 1
    Then ask about those classes. I don't see any other class in your question so I answered according to what I could see. – matt Dec 13 '16 at 21:22