if self.mapView.selectedAnnotations?.count != 0 {
if let selectedAnno = self.mapView.selectedAnnotations[0] as? MKAnnotation {
if (selectedAnno.isKindOfClass(AnnotationTypeOne)) {
annoType = "a"
} else if (selectedAnno.isKindOfClass(AnnotationTypeTwo)) {
annoType = "b"
}
}
}
第 2 行返回: fatal error :在展开可选值时意外发现 nil
我不明白为什么我会看到这个错误,因为我在分配它之前检查 if 语句是否为 nil。我还检查了 selectedAnnotations
的数组是否大于 0,但这似乎并没有改变什么。有什么想法吗?
最佳答案
那是因为这里:
if self.mapView.selectedAnnotations?.count != 0
您正在检查 count
是否不为零,但如果 selectedAnnotations
为 nil,则表达式计算为 nil
,这是不同的大于零。
正确的做法是:
if let annotations = self.mapView.selectedAnnotations {
if annotations.count != 0 {
if let selectedAnno = self.mapView.selectedAnnotations[0] as? MKAnnotation {
if (selectedAnno.isKindOfClass(AnnotationTypeOne)) {
annoType = "a"
} else if (selectedAnno.isKindOfClass(AnnotationTypeTwo)) {
annoType = "b"
}
}
}
}
旁注:nil != 0
是一个合法的表达式,计算结果为 true
。其他情况:
nil > 0 // false
nil < 0 // true
关于ios - 尽管在分配给变量之前进行了检查,但仍发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28489403/