gpt4 book ai didi

json - 不明确的使用 go 'subscript'

转载 作者:行者123 更新时间:2023-11-30 12:38:32 25 4
gpt4 key购买 nike

我正在尝试获取已在 php 脚本中编码为 json 的数据。

我的代码:

func getJson(completion: @escaping (Array<CarPark>) -> Void) {

activityIndicatior.center = self.view.center
activityIndicatior.hidesWhenStopped = true
activityIndicatior.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
view.addSubview(activityIndicatior)
self.activityIndicatior.startAnimating()

let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print("ERROR")
}
else
{
if let content = data
{

do{

let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

for index in 0..<myJson.count {

if let entry = myJson[index] as? NSDictionary{
let name = entry["Name"] as! String
let longitude = Double(entry["Longitude"] as! String)
let latitude = Double(entry["Latitude"] as! String)

let quiet = Int(entry["Quiet"] as! String)
let moderate = Int(entry["Moderate"] as! String)

let busy = Int(entry["Busy"] as! String)
let coordinate = CLLocationCoordinate2D( latitude: latitude!, longitude: longitude!)

print("coordinate lat is : \(coordinate.latitude)")
print("coordinate long is : \(coordinate.longitude)")
print("coordinate full is: \(coordinate)")
let tempPark = CarPark(name: name, latitude: latitude!, longitude: longitude!, quiet: quiet!, moderate: moderate!, busy: busy!, coordinate: coordinate, level: "Nil")
let level = tempPark.calcAvailability()
tempPark.level = level
print("Availability is \(tempPark.level)")
self.tempCarParks.append(tempPark)
// print("amount of parks: \(self.carParks.count)")
print("name of parks in array: \(self.tempCarParks[index].name)")
print("Availability is \(tempPark.level)")
}

}
completion(self.tempCarParks)

}
catch
{
print("Error")
}
}
}
}

task.resume()

}

我在以下行收到一条错误消息:“下标的使用不明确”:

如果让entry = myJson[index] 为? NS 字典{

我该如何解决这个问题?

最佳答案

既然您知道 myJson 是一个数组,为什么要将对象转换为未指定的 AnyObject

这会导致错误,编译器需要知道所有下标对象的具体类型。帮助编译器,然后编译器帮助你:

  let myJson = try JSONSerialization.jsonObject(with: content) as! [[String:Any]]

for entry in myJson { // don't use old-fashioned index based loops

let name = entry["Name"] as! String
...

.mutableContainers 在 Swift 中完全没用。

关于json - 不明确的使用 go 'subscript',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42562046/

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