在Swift中的MapView上计数注释

时间:2018-12-30 23:56:00

标签: ios swift mapkit mkannotation

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

我的代码如下:

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

给出错误:

  

可选类型'Int?'的值必须解包为type的值   'Int'

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

谢谢您的建议。

1 个答案:

答案 0 :(得分:1)

您必须打开可选的包装,例如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
}