2015-08-29 27 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 
...