2016-12-13 5 views
0

Ich versuche, die Klasse eines Objekts in einer Klassenhierarchie zu bestimmen. Ich bin verloren, um zu erklären, warum der Test im folgenden Beispiel fehlschlägt.Ermitteln des Typs der Swift-Klasse

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

Was ist viewFor hier? Wir können den Code, der es eingerichtet hat, nicht sehen, also haben wir keine Ahnung, wie sich dies auf die Ausgabe auswirkt. –

+0

was ist 'test'? – holex

+0

Dies könnte nützlich sein zu wissen: http://stackoverflow.com/a/40388434/3141234 – Alexander

Antwort

0

Sobald Sie gesagt haben

if let test = viewFor as? BasicLocation 

... Wenn das Test bestanden wird, stoppen. Sie wissen nun, dass test eine BasicLocation-Instanz ist oder dass wir den Test nicht bestanden hätten.

Alles andere, was Sie tun, ist nur dumm. Der Gleichheitsvergleich zwischen Metatypen ist nicht definiert.

+0

Der erste Test bestimmt nur, dass die Klasse ein Mitglied der Hierarchie ist. Es geht um die Klasse in der Hierarchie. – Stephen

+1

Fragen Sie dann nach diesen Klassen. Ich sehe keine andere Klasse in Ihrer Frage, also antwortete ich entsprechend, was ich sehen konnte. – matt

Verwandte Themen