2016-12-13 124 views
0

我想确定类层次结构中对象的类。我迷路了,解释为什么下面的例子中的测试失败了。确定Swift类的类型

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 
+0

什么是viewFor在这里?我们无法看到设置它的代码,因此我们不知道它是如何影响输出的。 –

+0

什么是测试? – holex

+0

这可能很方便知道:http://stackoverflow.com/a/40388434/3141234 – Alexander

回答

0

曾经,你说

if let test = viewFor as? BasicLocation 

...如果测试通过,停止。您现在知道test是BasicLocation实例,或者我们不会通过测试。

你所做的一切都是愚蠢的。元类型之间的平等比较是未定义的。

+0

第一个测试只确定该类是层次结构的成员。问题是层次结构中的哪个类。 – Stephen

+1

然后询问这些课程。我在你的问题中没有看到其他课,所以我根据我所能看到的答案回答。 – matt