代码之家  ›  专栏  ›  技术社区  ›  Fahim Parkar

检查是否为零,仍然崩溃说它为零

  •  -2
  • Fahim Parkar  · 技术社区  · 7 年前

    我的情况如下。

    var hotelType: String = "test"
    
    hotelType==hotelInfo.type!
    

    比如说 hotelInfo 结构如下。

    struct HotelInfo : Decodable {
        var type: String?
    }
    

    当应用程序崩溃时 hotelType 没有,我更新代码如下。

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

    然而静止应用程序正在崩溃 致命错误:在展开可选值时意外找到nil

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

    注: , 我有另一个解决方案(也很有效),但我肯定这是错误的。我将要做的是添加另一个变量,如下面的空白字符串中的making 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!) 这是我检查情况的地方。

    有人能给我指一个正确的方向来得到想要的数据吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   vacawama    7 年前

    是的,因为你是 强制展开 hotelInfo.type 之前 检查是否 nil :

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

    你做到了吗:

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

    它会起作用的。

    相反,使用 nil coalescing operator ?? :

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

    在筛选语句中:

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