如何从结构中访问特定值

时间:2018-10-26 12:37:33

标签: ios swift

我创建了一个结构UserModel.swift来存储json数据:-

struct UserModel {

    var id: Int = 0
    var uuid:Int = 0
    var user_name: String = ""
    var password: String = ""
    var name: String = ""
    var email: String = ""

    init(json: [String:Any]) {

        if let obj = json["id"] as? Int {
            self.id = obj
        }

        if let obj = json["uuid"] as? Int {
            self.uuid = obj
        }

        if let obj = json["user_name"] as? String {
            self.user_name = obj
        }

        if let obj = json["name"] as? String {
            self.name = obj
        }

        if let obj = json["email"] as? String {
            self.email = obj
        }
    }
}

现在,我使用Alamofire在我的ViewController.Swift文件中获取json,并通过创建一个变量存储了我的结构,我成功获取了json并将其存储在我的结构中。

var userModel = [UserModel]()
private func getList() {

    progressHUD.show(in: view, animated: true)

    //          let uuid = UserDefaults.standard.integer(forKey: "uuid")

    Alamofire.request(Constants.API.url("list_request?device_token=\(device_token ?? "")&uuid=794849"), method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON {
        (response:DataResponse<Any>) in
        self.progressHUD.dismiss()

        guard let json = response.result.value as? [String:Any] else {return}
        guard let data = json["data"] as? [[String:Any]] else {return}
        printD(data)
        guard let status = json["status"] as? Bool else { return}
        printD(status)

        if status == true {
            guard let data = json["data"] as? [[String:Any]] else {return}
            for userData in data {
                self.userModel.append(UserModel(json: userData))
                printD(self.userModel)
            }
            CommonClass.shared.showSuccessMessage("\(json["msg"] as? String ?? "")", inViewController: self)
        }

        else if status == false {
            CommonClass.shared.showErrorMessage("\(json["msg"] as? String ?? "")", inViewController: self)
        }
        else  {
            CommonClass.shared.showErrorMessage("Server Connection Error. Please try again later", inViewController: self)
        }

        self.tableView.reloadData()
    }
}

现在我遇到的问题是我必须在同一类的另一个api中使用userModel数据,但我不知道该怎么做。在rejectRequest()函数中,我需要访问一些结构数据,但是我不知道该怎么做。请帮忙吗?

private func rejectRequest() {
    let user = userModel // I need to use userModel data for parameter 
    let param: [String:Any] = ["from_user": "", "to_user": "", "request_id": "", "device_token": device_token ?? ""]

    Alamofire.request(Constants.API.url("end_request"), method: .post, parameters: param, encoding: JSONEncoding.default, headers: nil).responseJSON {
        (response:DataResponse<Any>) in

    }
}

1 个答案:

答案 0 :(得分:1)

创建一个结构来保存在应用程序之间共享的通用数据。这是一个DataController的示例,该示例可以容纳不同的模型或模型的数组/字典:

struct DataController {

    // MARK: - User management

    struct Users {
        static var users: [User] = []
        static var currentUser: User = User()

        static func addUser(_ user: User) {
             users.append(user)
        }

        static func findUserById(_ id: Int) -> User? {
            // Find the users that match the id (should only be one!)
            let users = user.filter { $0.id = id }
            return users.count == 1 ? users[0] : nil
        }
    }
}

添加用户:

 DataController.Users.addUser(user)

通过以下方式从其他地方访问

DataController.Users.currentUser

通过ID查找用户:

if let user = DataController.Users.findUserById(id) {
     ... do stuff ... 
}

偶然地,在解析JSON数据时使用guard语句可能更简单:

init(json: [String:Any]) {

    guard 
        let id = json["id"] as? Int,
        let uuid = json["uuid"] as? Int,
        let user_name = json["user_name"] as? String,
        let name = json["name"] as? String,
        let email = json["email"] as? String
    else {
        return // Fail
    }

    self.id = id
    self.uuid = uuid
    self.user_name = user_name
    self.name = name
    self.email = email
}