首页 > 解决方案 > 外部函数字典中相同键的访问值

问题描述

我想访问名为 name 的字典的相同键,但我无法更改键的值,因为它在服务器上:这是我的代码:

 func infoUser(complition:@escaping ([String:Any]) -> Void) {
    let url = URL(string: "\(offerUrl)/api/user")! //change the url
                //create the session object
                let session = URLSession.shared
                //now create the URLRequest object using the url object
                var request = URLRequest(url: url)
                request.httpMethod = "GET" //set http method as POST
                request.addValue("application/json", forHTTPHeaderField: "Content-Type")
                request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue( "bearare \(profileKeychain["token"]!)", forHTTPHeaderField: "Authorization")
                let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
                    guard error == nil else {
                        return
                    }
                    guard let data = data else {
                        return
                    }
                    print("data is : \(data)")
                    do {
                        //create json object from data
                        if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                            print("this is json format: \(json)")
                        // handle json ...
                            guard let YourName = json["name"] as? String else { return }
                            guard let YourAddress = json["address"] as? String else { return }
                            guard let YourPhone = json["telephone"] as? String else { return }
                            guard let YourEmail = json["email"] as? String else { return }
                            guard let city = json["city"] as? [String: Any] else { return }
                            guard let title = city["title"] as? String else { return }
                            guard let country = json["country"] as? [String: Any] else { return }
                            guard let names = country["name"] as? String else { return }
                            let dict = ["name":YourName,"address":YourAddress,"telephone":YourPhone,"email":YourEmail,"city":city,"title":title,"country":country,"name" : names] as [String : Any]
                            
                            complition(dict)
                        }
                     
                    } catch let error {
                        print("error is this : \(error.localizedDescription)")
                    }
                })
                task.resume()
}

我想访问国家/地区名称的值,其名称中的键类似于用户的名称,这也是我使用它的完成处理程序,我从 viewdidLoad() 函数中调用它:

override func viewDidLoad() {
    super.viewDidLoad()
    if profileKeychain["token"] != "" {
        infoUser { dict in
            DispatchQueue.main.async {
            self.yourNamelbl.text = dict["name"] as? String
            self.yourPhonelbl.text = dict["telephone"] as? String
            self.yourCitylbl.text = dict["title"] as? String
            self.yourMaillbl.text = dict["email"] as? String
            self.yourAddresslbl.text = dict["address"] as? String
                
            // this line
            self.countryNamelbl.text = dict["name" ] as? String }}}

在模拟器中,国家名称和用户名称在标签中是相同的,但我不想发生这种情况,你的想法是什么?

感谢关注

标签: iosswift

解决方案


您正在覆盖"name"键的值。

let dict = [
    "name": YourName, // First write happens here
    "address": YourAddress,
    "telephone": YourPhone,
    "email": YourEmail,
    "city": city,
    "title": title,
    "country": country,
    "name" : names // Second write, The problem is here
] as [String: Any]

更新

你已经name嵌套在country字典里面,所以你不需要在顶层再存储一次。

您可以从上面的代码部分中删除第二个写入,"name": names并像在viewDidLoad().

let country = dict["country"] as? [String: Any]
self.countryNamelbl.text = country?["name"] as? String

推荐阅读