我正在使用Xcode 9.2和Swift 4.如何检查返回的json数据是否为空?现在,它给了我错误Type 'Any' has no subscript members的行if json[0]["data"]
var json: NSMutableArray = []
var newsArray: NSMutableArray = []
let url = URLFactory()
var data = try! NSData(contentsOf: url.getURL()) as Data
do {
json = try JSONSerialization.jsonObject(with: data, options: []) as! NSMutableArray
if json[0]["data"] {
// data is not null
}
} catch let error as NSError {
// handle error
}
Run Code Online (Sandbox Code Playgroud)
我的JSON返回如下内容:
{
"data":
[
{
"news_id":123,
"title":"title",
"news_date":"2017-02-08 21:46:06",
"news_url":"url",
"short_description":"description",
"category_id":4,
"category_name":"Health",
"latlng":
[ …Run Code Online (Sandbox Code Playgroud) 我正在尝试检查数组是否categories包含数字1 ,例如Int因为categories = [Int]()categories = {1, 2, 3, 4, 5}
我尝试了以下代码,这给了我错误 Binary operator '==' cannot be applied to operands of type 'Any' and 'Int'
if categories.contains (where: {$0 == 1}) {
// 1 is found
}
Run Code Online (Sandbox Code Playgroud)
也尝试了没有下面的哪里和方括号的尝试,这给了我同样的错误
if categories.contains { $0 == 1 } {
// 1 is found
}
Run Code Online (Sandbox Code Playgroud)
我尝试只使用以下元素,这给了我错误 Missing argument label 'where:' in call
if categories.contains(1) {
// 1 is found
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?