我正在尝试确定类层次结构中对象的类。我很想解释为什么下面例子中的测试失败。
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 :(得分:0)
说完后
if let test = viewFor as? BasicLocation
......如果该测试通过,请停止。您现在知道test
是BasicLocation实例,或者我们不会通过测试。
你正在做的其他事情都很愚蠢。元类型之间的平等比较是不确定的。