2016-12-13 118 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