【问题标题】:Alamofire: unexpectedly found nil while unwrapping an Optional valueAlamofire:在展开可选值时意外发现 nil
【发布时间】:2017-05-12 08:00:34
【问题描述】:

美好的一天。

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

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

我从字典中读取的代码 sn-p 如下:

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 的结果进行一些验证检查,如上所示。

问候

【问题讨论】:

  • as? Decimal! 不要强制展开。将! 替换为另一个级别的if let 并处理nil 的可能性。
  • 美好的一天。谢谢你的回复,你能给我一个替换“!”的例子吗?使用“如果让”进行零验证?问候
  • 您自己的代码中有一个示例。 :) 这也已经在各处进行了解释,搜索“可选”和“可选绑定”(这是if let 系统的名称)。
  • 您正在尝试将 LowRate 字符串设为十进制,请检查强制转换,是否将十进制更改为?字符串和类型种姓它适当的类型
  • 您好,感谢您的回复,它大部分时间都是小数,也可能为空。我需要验证如果它不是小数,如果它是 null 我需要默认它

标签: ios json swift xcode alamofire


【解决方案1】:

你可以这样做。(更新)

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

【讨论】:

  • 谢谢! !(variable is NSNull) 非常适合我
【解决方案2】:

美好的一天

感谢所有帮助我找到答案的贡献。最终起作用的是与上面非常相似的东西,我必须使用 NSNumber 对象,然后稍后将其转换为小数,请参阅下面的代码。

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

 HList._LowRate = LowRate

}else{

   print("Null")

}

问候

【讨论】:

    【解决方案3】:

    您的 json 数组中只有一个对象。我的价值是多少?如果大于 0 就会崩溃。

    【讨论】:

    • 试试 HotelList[i]["LowRate"] as?十进制?
    • 您好,我现在试试这个并回复您
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2016-10-18
    • 2017-04-09
    • 2018-09-22
    相关资源
    最近更新 更多