2017-07-19 45 views
1

我得到一個Json獲取請求,我的值是一個數組,因此爲什麼我把我的JSONSerializaion as? NSArray根據值更改Swift語句的類型

但是,有時在我的後端值不被作爲一個數組,但一本字典,所以我怎麼能檢查我的值的類型,並相應地改變as?,如果讓任何意義

do{ 
    let json = try 
    JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray //This is what I want to change 

有時值作爲字典送到所以我怎樣才能讓我的應用程序知道執行的as? NSDictionary代替as? NSArray

回答

2

我可能會使用一個switch區分可能性:

do { 
    switch try JSONSerialization.jsonObject(with: arrayJson, options: .mutableContainers) { 
    case let array as NSArray: 
     // Use array here. For example: 
     print("got an array of \(array.count) elements") 

    case let dictionary as NSDictionary: 
     // Use dictionary here. For example: 
     print("got a dictionary with keys: \(dictionary.allKeys)") 

    case let other: 
     print("I got something I didn't understand: \(other)") 
    } 
} catch { 
    print(error) 
} 

,如果你想你也可以使用多個if let分支:

do { 
    let object = try JSONSerialization.jsonObject(with: arrayJson, options: .mutableContainers) 
    if let array = object as? NSArray { 
     print("got an array of \(array.count) elements") 
    } else if let dictionary = object as? NSDictionary { 
     print("got a dictionary with keys: \(dictionary.allKeys)") 
    } 
} catch { 
    print(error) 
} 
1

使用另購的結合

if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [Any] { 
    // handle the array  
} else if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any] { 
    // handle the dictionary 
}