gpt4 book ai didi

ios - Swift:如果让语句无法处理空数组

转载 作者:可可西里 更新时间:2023-11-01 00:52:31 25 4
gpt4 key购买 nike

我有一个使用 Foursquare API 下载 JSON 数据的应用程序。我正在使用 NSURLSession 和带有完成 block 方法的 dataTaskWithRequest 来获取数据。我得到的数据很好,但有时名为 groups 的嵌套数组可能为空。当我像下面这样解析 JSON 时,由于某种原因,我的条件语句没有像我期望的那样处理空数组。而不是将数组评估为空并继续执行 if let...else 语句的“else”部分,而是通过运行时错误声明:index 0 beyond bounds of empty array

if let response: NSDictionary = data["response"] as? [String: AnyObject],
groups: NSArray = response["groups"] as? NSArray,
// Error here \|/ (sometimes groups array is empty)
dic: NSDictionary = groups[0] as? NSDictionary,
items: NSArray = dic["items"] as! NSArray {

}

else {

// Never gets here. Why?
// IF the groups array is empty, then the if let should return
// false and drop down to the else block, right?
}

我是 Swift 的新手,有人能告诉我为什么会这样,我能做些什么来解决这个问题?谢谢

最佳答案

如果数组为空,您必须在 if let 语句之外显式检查,因为

空数组永远不是可选的

if let response = data["response"] as? [String: AnyObject], groups = response["groups"] as? NSArray {
if !groups.isEmpty {
if let dic = groups[0] as? NSDictionary {
items = dic["items"] as! NSArray
// do something with items
println(items)
}
}
} else ...

向下转换类型时可以省略所有类型注释

但是,您可以使用 where 子句执行检查,这适用于 Swift 1.2 和 2

if let response = data["response"] as? [String: AnyObject],
groups = response["groups"] as? [AnyObject] where !groups.isEmpty,
let dic = groups[0] as? NSDictionary,
items = dic["items"] as? NSArray {
// do something with items
println(items)
} else {...

关于ios - Swift:如果让语句无法处理空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32283954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com