JSON解析后访问结构数据,Swift

JSON解析后访问结构数据,Swift,swift,struct,get,alamofire,codable,Swift,Struct,Get,Alamofire,Codable,我陷入了以下困境: 我已经运行了这个代码 AF.request(url, method: .get).responseDecodable(of: UserInfo.self) { response in debugPrint(response) } 我将JSON解析为以下结构: struct UserInfo: Codable { let totalCount: Int let incompleteResults: Bool let items: [Item] enu

我陷入了以下困境: 我已经运行了这个代码

AF.request(url, method: .get).responseDecodable(of: UserInfo.self) { response in
        debugPrint(response)
    }
我将JSON解析为以下结构:

struct UserInfo: Codable {
let totalCount: Int
let incompleteResults: Bool
let items: [Item]

enum CodingKeys: String, CodingKey {
    case totalCount = "total_count"
    case incompleteResults = "incomplete_results"
    case items
}}

struct Item: Codable {

let id: Int
let userName: String

enum CodingKeys: String, CodingKey {
    case id
    case userName = "userName"
}}
例如,如何访问用户名字段

该结构在我的类之外,我希望将其归档到另一个.swift文件中


多谢各位

您要使用的是回调,将数据发送回调用networkRequestFunction的函数

  func makeRequest() {
            someRequest(url: "thisURL") { (userInfo, error) in
                guard let userInfo = userInfo else {
                    // present error
                    return
                }

                // Now you have your userStruct
                print(userInfo)
            }
        }


        func someRequest(url: String, callback: @escaping ((UserInfo?, AFError?) -> ())) {
                AF.request(url, method: .get).responseDecodable(of: UserInfo.self) { response in
                    switch response.result {
                    case .success(let info):
// This is where i missed that you already had decoded it, no need to guard let here
                        callback(info, nil)
                    case .failure(let error):
                        callback(nil, error)
                    }
            }
        }

我真的很感激你的回答,但我是一个安静的初学者,我不是很好。我在数据上遇到以下错误:条件绑定的初始值设定项必须具有可选类型,而不是“UserInfo”,而且为了确保,对于Model,您是指我的struct UserInfo?顺便说一句,通过调试器中的代码,我看到了我的UserInfo和我想要的字段,但我无法访问它们。很抱歉,我误读了您的一些代码。我已经完整地编辑了我的回答谢谢你的时间!你真是太好了!!我可以再问一个问题吗?如果我需要访问另一个.swift文件中的用户名字段,该怎么办?你的代码正在工作,这超出了我的问题范围!老实说,我不知道如何访问主文件中的用户名字段。。。