2015-08-29 25 views
2

我有一个使用Foursquare API下载JSON数据的应用程序。我使用NSURLSessiondataTaskWithRequest以完成块方法来获取数据。我得到的数据很好,但有时一个名为groups的嵌套数组可能是空的。而当我通过下面的JSON解析时,出于某种原因,我的条件语句没有像我期待的那样处理空数组。相反,阵列评价为空,在进行if let...else语句的“其他”部分,如果不是得来运行时错误陈述的:index 0 beyond bounds of empty arraySwift:如果let语句无法处理空数组

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

我是比较新的雨燕,谁能告诉我这是为什么发生的以及我能做些什么来解决这个问题?由于

+0

你尝试nsnull检查阵列响应对象的值? – Loxx

+0

意思是实际测试类类型NSNull? – Loxx

+0

我知道我可以这样做,我只是想在这里理解Swift。在我看来,如果它是空的(意思是错误的),它会这样评价。而且,如果语句通常会这样做,他们就会下降到else块。我想如果让Swift的话,我会有点困惑。 –

回答

4

你要如果数组是空的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 {... 
+0

我想这就是我必须要做的,并且已经做到了。我只是认为,随着斯威夫特的力量,如果让我们的预期目的实际上会处理我的情况。感谢您的回答。 –

0

在命令之间使用运算符&&

例如,这会不会崩溃:

var a = 4; 
var c = 5; 
var array = Array<Int>(); 

if a > 2 && c > 10 && array[0] != 0 { 

} 
0

确保数组不试图访问之前空:

if let response: NSDictionary = data["response"] as? [String: AnyObject], 
    let groups: NSArray = response["groups"] as? NSArray where groups.count > 0 { 
     if let dic: NSDictionary = groups[0] as? NSDictionary, 
      let items: NSArray = dic["items"] as? NSArray { 
      // Do something.. 
      return // When the 2nd if fails, we never hit the else clause 
     } 
} 

// Do logic for else here 
...