【发布时间】: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