swift - 检查零,仍然崩溃说它的零
问题描述
我有一个条件如下。
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!)
这是我检查条件的地方。
有人可以指出我正确的方向以获得所需的数据。
解决方案
是的,这仍然会崩溃,因为您在检查它是否是之前强制解包 :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
}
推荐阅读
- set - 在 MIPS 中编码基本指令格式
- swift - AKMIDICallbackInstrument 实现问题
- c++ - 什么数据类型用于自定义基于堆栈的分配器的缓冲区?
- postgresql - 为什么 syslog-ng 将日志插入多行表中?
- shell - 使用多个并发 MPI LAMMPS 作业减慢速度
- c# - .Net Core 2.1 的 JwtSecurityTokenHandler() 问题;
- python - 浏览特定页数的文件
- python-3.x - 如何将 pytesseract 部署到 Heroku
- delphi - 我可以在 TJvMail 中设置发件人的地址吗
- python - 在遍历行时获取 KeyError:61