在 Swift 中计算 MapView 上的注释

Count Annotations on MapView in Swift

完成从数组中将注释放置在地图上的循环后,我想计算注释的数量。

我的代码如下:

let anCount = self.mapView.annotations?.count
            if (anCount > 1) {
//do something
            }

给出错误:

Value of optional type 'Int?' must be unwrapped to a value of type 'Int'

修复建议产生了其他错误。计算地图注释数量的正确方法是什么。

感谢您的任何建议。

您必须打开可选的包装,例如使用 if let,然后您可以将其与 > 1 测试结合在一个 if 语句中:

if let anCount = mapView.annotations?.count, anCount > 1 {
    //do something
}

但是 annotations 不是可选的(至少在当前的 iOS 版本中),所以您可能会这样做:

let anCount = mapView.annotations.count
if anCount > 1 {
    //do something
}