Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/103.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 解析API获取的Json后,无法将其分配给Swift中的变量_Ios_Json_Iphone_Swift4 - Fatal编程技术网

Ios 解析API获取的Json后,无法将其分配给Swift中的变量

Ios 解析API获取的Json后,无法将其分配给Swift中的变量,ios,json,iphone,swift4,Ios,Json,Iphone,Swift4,我使用swift4创建了一个iOS应用程序 我有一个问题。 解析使用API获取的Json后,无法将其分配给var stores:[categories.stores]?。打印值为nil struct categories : Codable { let id : Int let name : String let stores : [stores] struct stores : Codable { let id : Int let name : String let

我使用swift4创建了一个iOS应用程序

我有一个问题。 解析使用API获取的Json后,无法将其分配给
var stores:[categories.stores]?
。打印值为nil

struct categories : Codable {
let id : Int
let name : String
let stores : [stores]

struct stores : Codable {
    let id : Int
    let name : String
    let location : String
    let price : String
    let open_time : String
    let closed_day : String
    let photos : [photos]
    let tags : [tags]

    struct photos:Codable {
        let id : Int
        let path : String
    }

    struct tags:Codable {
        let id : Int
        let name : String
    }
}
}
但是print
let json=try decoder.decode(categories.self,from:data)
,我可以得到json数据

没有错误。所以我不知道为什么我不能代替

请帮帮我

StoreListViewController

class StoreListViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var TableView: UITableView!


var category_id = ""
let cellReuseIdentifier = "cell"
// use json 
var stores : [categories.stores]?

override func viewDidLoad() {
    super.viewDidLoad()
    TableView.delegate = self
    TableView.dataSource = self

    let url = URL(string: "http://127.0.0.1:8000/search/api/category?category_id=" + category_id)
    let request = URLRequest(url: url!)
    let session = URLSession.shared

    let encoder: JSONEncoder = JSONEncoder()
    encoder.dateEncodingStrategy = .iso8601
    encoder.outputFormatting = .prettyPrinted

    session.dataTask(with: request){(data, response, error)in if error == nil,
        let data = data,
        let response = response as? HTTPURLResponse{

        let decoder: JSONDecoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        do {

            let json = try decoder.decode(categories.self, from: data)

            // in to stores variable
            self.stores = json.stores

            DispatchQueue.main.async {
                self.TableView.reloadData()
            }
        } catch {
            print("error:", error.localizedDescription)

        }

        }

        }.resume()

    print(stores as Any)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return stores?.count ?? 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as? TableViewCell
        else {
            fatalError("The dequeued cell is not an instance of TableViewCell.")
    }

    cell.storeName.text! = stores![indexPath.row].name
    cell.storeLocation.text! = stores![indexPath.row].location


return cell
}

}
数据模型

struct categories : Codable {
let id : Int
let name : String
let stores : [stores]

struct stores : Codable {
    let id : Int
    let name : String
    let location : String
    let price : String
    let open_time : String
    let closed_day : String
    let photos : [photos]
    let tags : [tags]

    struct photos:Codable {
        let id : Int
        let path : String
    }

    struct tags:Codable {
        let id : Int
        let name : String
    }
}
}

在关闭前我在一家公司工作

它打印
nil
,因为
print
行在闭包之外,将在返回数据之前执行。把线放在封口内。如果未显示任何数据,则错误必须位于其他位置。请用大写字母和单数形式命名结构(
struct Photo:Codable
)。结构的一个实例是一个
Photo
而不是一个
Photos
。我明白了。我改变了。非常感谢您:并将数据源数组
stores
声明为非可选
var stores=[Category.Store]()
,以摆脱一堆难看的问题、感叹号和奇怪的语法,如
stores?.count??0