ios - 尽管在分配给变量之前进行了检查,但仍发现 nil

标签 ios swift

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/

相关文章:

ios - 从“TCHMessageType”强制转换为无关类型“String”总是失败

ios - 删除 CloudKit 记录 Swift 4

swift - NSCoding 在 Swift 中不起作用

ios - Parse.com PFUser signUpInBackgroundWithBlock : block not being called on first tap

swift - 自定义 tableviewcell 中的 PieChartView

swift - macOS 菜单栏应用程序 : main menu not being displayed

ios - Swift 4 Codable 从字符串解码 URL

ios - 如何一次性 AirPrint 多个打印格式化程序?

ios - 是否有一个集中维护的手机/平板电脑和操作系统组合列表,可以指导合理的设备列表进行测试

objective-c - 为 Watch OS2 创建扩展委托(delegate)类