首页 > 解决方案 > 检查零,仍然崩溃说它的零

问题描述

我有一个条件如下。

var hotelType: String = "test"

hotelType==hotelInfo.type!

假设hotelInfo有如下结构。

struct HotelInfo : Decodable {
    var type: String?
}

由于应用程序崩溃说那hotelType是零,我更新代码如下。

hotelType==(hotelInfo.type!==nil ? "" : hotelInfo.type!)

但是仍然应用程序崩溃说致命错误:在展开可选值时意外发现 nil

有没有办法在检查实际数据之前检查零。

注意:我有替代解决方案(也可以正常工作),但我肯定觉得这是错误的。我要做的是添加另一个变量,如下所示将 nil 设置为空白字符串并检查该变量。

struct HotelInfo : Decodable {
    var type: String?
    var typeFixed: String? {
        get {
            if (self.type==nil) {
                return ""
            }
            return self.type
        }
    }
}

& 使用这个变量

hotelType==hotelInfo.typeFixed!

最重要的

我在过滤器中这样做,所以我不能使用if let语句(这是实际代码,但我给出了上面的简单逻辑,因为数据非常复杂)

finalArray = finalArray.filter { hotels in
    hotels.infos?.contains { roomInfo in
        selectedChain.contains { rt in
            rt == (roomInfo.hotelChain?.supplierHotelChain!==nil ? "" : roomInfo.hotelChain?.supplierHotelChain!)
        }
        } ?? false
}

rt == (roomInfo.hotelChain?.supplierHotelChain!==nil ? "" : roomInfo.hotelChain?.supplierHotelChain!)这是我检查条件的地方。

有人可以指出我正确的方向以获得所需的数据。

标签: swiftnullswift4

解决方案


是的,这仍然会崩溃,因为您在检查它是否是之前强制解包hotelInfo.type nil

hotelType==(hotelInfo.type!==nil ? "" : hotelInfo.type!)

你做过:

hotelType == (hotelInfo.type == nil ? "" : hotelTypeInfo.type!)

它会奏效的。

相反,使用nil 合并运算符??

hotelType == (hotelInfo.type ?? "")

在您的过滤器语句中:

finalArray = finalArray.filter { hotels in
    hotels.infos?.contains { roomInfo in
        selectedChain.contains { rt in
            rt == (roomInfo.hotelChain?.supplierHotelChain ?? "")
        }
    } ?? false
}

推荐阅读