【问题标题】:Swift: cannot convert value of type string to expected argument type stringSwift:无法将类型字符串的值转换为预期的参数类型字符串
【发布时间】:2017-12-30 08:33:14
【问题描述】:

在 swift 3 方面需要帮助。我得到了

无法将字符串类型的值转换为预期的参数类型字符串

 func authKMA(text: String) {

     let base = "http://api.kma1.biz/?method=auth"
     let userlogin = "&username=vostok3r@gmail.com"
     let userpass = "&pass=0000"
     _ = ""
     _ = ""
     let auth = base + userlogin + userpass

     let url = URL(string: auth)!

     URLSession.shared.dataTask(with: url) { (data, _, _) in
        guard let gotdata = data else {
            print("Сервер не отвечает")
            return
        }

        guard  let jsonAny = try? JSONSerialization.jsonObject(with: gotdata, options: []) else {
            print("Сервер не дал информацию по аккаунту")
            return
        }

        guard let json = jsonAny  as? [String: Any] else {
            return
        }

        guard let authhasher = json.index(of: "authhash") else {
            return
   //ERROR: cannot convert value of type string to expected argument type string//  
        }    
        print(authhasher)
    }.resume()
}
}

【问题讨论】:

  • 这似乎是一个奇怪的错误,但Dictionary 没有方法index(of:),所以该行不应该工作。您想使用let authhasher = json.index(of: "authhash") 实现什么目标?
  • @DávidPásztor 我只是一个新手并试图从 json 数组中获取“authhash”值。
  • @LeonKazakov 是字典,而不是数组。您可以按照他的回答中提到的 toddg 访问“authhash”。

标签: swift string type-conversion


【解决方案1】:

正如 Dávid Pásztor 所说,Dictionary 没有 index(of:) 方法。如果您要做的只是从 json 字典中提取 authhash 值,则可以使用下标表示法访问您的值:

guard let authhasher = json["authhash"] as? String else {
        return  
}
print(authhasher)    

【讨论】:

  • 太棒了!很高兴它对你有效。点击复选标记以接受此答案并向未来的观众表明它解决了您的问题。
猜你喜欢
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多