swift - 确定 Swift 类的类型

标签 swift types introspection

我正在尝试确定类层次结构中对象的类。我无法解释为什么下面示例中的测试失败。

    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/

相关文章:

ios - 向 Firebase 发送数据时出现错误 "InvalidFirebaseData"

ios - 为 swift 应用程序创建存档的段错误

swift - 将 NSSlider 增加 0.1? macOS, swift

types - 如何在 TradingView pinescript 中实现条件长度移动平均线?

java - 根据输入字符串决定 var 类型

objective-c - 编译时 block 会发生什么?我可以在运行时创建一个 block 吗?

ruby - 如何检查 ruby​​ 方法中可选参数的默认值是多少?

ios - 带 NavigationController 的 SWRevealViewController - Swift 3

C++ - unique_ptr 的转换/更改类型

python - 声明类的 SQLAlchemy 自省(introspection)