Alamofire:在解开Optional值时意外地发现了nil

时间:2017-05-12 08:00:34

标签: ios json swift xcode alamofire

美好的一天。

我有一个iOS Swift应用程序,它与已经创建API的公司进行通信,并与使用Alamofire进行通信。我遇到的问题是API可能会在一段时间内返回空值,这会导致以下问题:

"致命错误:在展开可选值时意外发现nil"

我从字典中读取的代码片段如下:

if let LowRate = HotelList[i]["LowRate"] as? Decimal!{ 
    HList._LowRate = LowRate
}

我已经回顾了多个问题和谷歌网站但是我需要一种方法在处理之前检查字典中的对象为null,或者我需要设置某种类型的默认值。

Json null示例如下

 HotelData = "<null>";
        HotelList =(
           {
                Address1 = "124 Oceanview Road";
                Address2 = Oneroa;
                BookingUrl = "<null>";
                City = " Auckland";
                Country = "New Zealand";
                CurrencyCode = "<null>";
                DateViewed = "<null>";
                Description = "<null>";
                Directions = "<null>";
                Distance = "<null>";
                GeoPoint = "<null>";
                HighRate = "<null>";
                ImageUrl = "<null>";
                LowRate = "<null>";
                MinChildAge = "<null>";
                Name = "The Oyster Inn";
                NavUrl = "<null>";
                PostalCode = "<null>";
                State = "<null>";
                WebsiteUrl = "<null>";
                distance = "<null>";
                hotelID = 130;
                isActive = 1;
                isBlocked = 0;
                isChildrenAllowed = "<null>";
                isFavorite = 0;
                isPromoNotified = 0;
                showDouble = "<null>";
}
         );
        RowCount = 11;
        hasError = 0;
    };

我正在使用Alamofire作为我的json,除非在可能返回null的20个字段之一中返回null,否则它会起作用。

在展开可选项时,任何人都可以协助我对null的结果进行一些验证检查。

此致

2 个答案:

答案 0 :(得分:0)

这是你如何做到的。(更新)

if let lowRate = json["LowRate"], !(lowRate is NSNull){
   print(lowRate)
}else{
   print("null")
}

答案 1 :(得分:0)

美好的一天

感谢所有帮助我找到答案的贡献。到底有什么效果与上面非常类似,我不得不使用一个NSNumber对象,然后将其转换为小数,请参阅下面的代码。

if let lowRate = HotelList[i]["LowRate"] as? NSNumber{  

 HList._LowRate = LowRate

}else{

   print("Null")

}

此致