【问题标题】:Determining the type of Swift class确定 Swift 类的类型
【发布时间】:2016-12-13 15:55:23
【问题描述】:

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

    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

【问题讨论】:

  • 这里的viewFor是什么?我们看不到设置它的代码,所以我们不知道它如何影响输出。
  • 什么是test
  • 这可能很方便知道:stackoverflow.com/a/40388434/3141234
  • 在编写的代码中,viewFor as? BasicLocation 应该总是失败。 BasicLocation 没有实现 MKAnnotation。如果它确实实现了MKAnnotation,那么它实现了NSObjectProtocol,这完全改变了这个问题。 NSObject 子类允许任意 Swift 子类不允许的内省。如果这是一个 NSObject,请参阅 .isMember(of:)

标签: swift types introspection


【解决方案1】:

你说过

if let test = viewFor as? BasicLocation

...如果该测试通过,请停止。您现在知道test 是一个BasicLocation 实例,否则我们不会通过测试。

你所做的一切都是愚蠢的。元类型之间的相等比较是未定义的。

【讨论】:

  • 第一个测试仅确定该类是层次结构的成员。问题在于层次结构中的哪个类。
  • 然后询问这些课程。我在你的问题中没有看到任何其他课程,所以我根据我能看到的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多