ios - Alamofire:在展开可选值时意外发现 nil

标签 ios json swift xcode alamofire

美好的一天。

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

“ fatal error :在展开可选值时意外发现 nil”

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

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

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

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;
    };

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

任何人都可以帮助我在展开可选时对如上所示的 null 结果进行一些验证检查。

问候

最佳答案

这就是你如何做到这一点。(更新)

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

关于ios - Alamofire:在展开可选值时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43932468/

相关文章:

c# - 使用 Windows C# 第三方程序更改 IOS 应用程序名称

ios - 如何在应用增加边界宽度的自定义渲染时保留 ArcGIS map 中填充的颜色

ios - 加载 NibNamed 时崩溃(_ :owner:options:)

iphone - 如何获取相机屏幕上指定点像素的RGB值?

ios - UIButton Outlet 设置标题 Swift

json - 使用调查问题运行 JSON 字典循环 SWIFT

javascript - 如何从Json中删除特殊字符而不解析

json - 如何从json数据创建hive表

ios - 如何在 Firebase for iOS 应用程序中保存 "posts"(不是服务器 POST 但更像是公告板)

ios - swift 4 : back button in SWRevealViewController