我正在尝试确定类层次结构中对象的类。我无法解释为什么下面示例中的测试失败。
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
最佳答案
一旦你说了
if let test = viewFor as? BasicLocation
...如果测试通过,则停止。您现在知道 test
是一个 BasicLocation 实例,否则我们将无法通过测试。
你所做的其他一切都是愚蠢的。元类型之间的相等比较未定义。
关于swift - 确定 Swift 类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41125290/