【问题标题】:What is the proper way to use if _ is _ or .isKind(of: )如果 _ 是 _ 或 .isKind(of: ),正确的使用方法是什么
【发布时间】:2019-07-09 20:30:37
【问题描述】:

我一直在努力实现这段代码。我正在将一些遗留代码转换为 swift,但我无法让 [annotation isKindofClass] 等价物工作。

最初我选择了类似的东西(给了我错误

mapView.annotations.forEach {
        if !$0.isKind(of: MKUserLocation) {
            self.mapView.removeAnnotation($0)
        }
    }

但我在this 帖子上读到 swift 有不同的处理方式。

mapView.annotations.forEach {
        if !$0 is MKUserLocation {
            self.mapView.removeAnnotation($0)
        }
    }

这给了我错误:无法将 MKAnnotation 类型的值转换为预期的参数类型 BOOL

【问题讨论】:

    标签: ios swift


    【解决方案1】:
    public func isKind(of aClass: AnyClass) -> Bool
    

    这个函数需要AnyClass作为参数,你必须传递一个类,使用.self

        mapView.annotations.forEach {
            if !$0.isKind(of: MKUserLocation.self) {
                self.mapView.removeAnnotation($0)
            }
        }
    

    使用is时,必须用括号括起来:

        mapView.annotations.forEach {
            if !($0 is MKUserLocation) {
                self.mapView.removeAnnotation($0)
            }
        }
    

    您正在检查 $0 的布尔值,而不是 is 表达式,因此出现错误。

    【讨论】:

      【解决方案2】:

      总之你可以做到With

      mapView.annotations.remove(where:{ !($0 is MKUserLocation) } )
      

      【讨论】:

        猜你喜欢
        • 2016-11-28
        • 1970-01-01
        • 1970-01-01
        • 2017-01-07
        • 1970-01-01
        • 2021-11-24
        • 2021-09-23
        • 2017-04-07
        • 2013-01-09
        相关资源
        最近更新 更多