Swift &引用;参数类型字符串不符合预期的类型解码器";尝试使用可编码协议获取JSON时
我试图使用Swift 4Swift &引用;参数类型字符串不符合预期的类型解码器";尝试使用可编码协议获取JSON时,swift,codable,Swift,Codable,我试图使用Swift 4Codable功能获取JSON,但由于某些原因,它会产生一个错误,显示: 参数类型字符串不符合预期的类型解码器 这是我的密码: import UIKit struct aURL : Codable { let title: String let aurl: String // let style: URLStyle } class SectionTableViewController: UITableViewController {
Codable
功能获取JSON,但由于某些原因,它会产生一个错误,显示:
参数类型字符串不符合预期的类型解码器
这是我的密码:
import UIKit
struct aURL : Codable {
let title: String
let aurl: String
// let style: URLStyle
}
class SectionTableViewController: UITableViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
do {
let queue = DispatchQueue(label: "cool")
queue.async {
if let somedata = try? Data(contentsOf: URL(from: "http://json-schema.org/example/geo.json")!, options: []) {
let json = try? JSONSerialization.jsonObject(with: somedata, options: [])
print(json)
DispatchQueue.main.async {
}
}
}
} catch let error as NSError {
print("Error: \(error)")
}
}
如果我尝试使用Xcode建议修复,如图所示:
我得到这个错误:
无法将“Swift.String”(0x1015acf68)类型的值强制转换为“Swift.Decoder”(0x1015ec460)
这是一个误会
URL
API
init(from decoder: Decoder) throws
只能在自定义结构中使用从给定的解码器
创建URL,非常类似于类相关的NSCoding
协议的init(coder
API)
在上下文中,要从字符串创建URL,必须使用
URL(string
URL(string: "http://json-schema.org/example/geo.json")!
这正是错误消息所说的:我期待一个解码器
,但我得到一个字符串
重要提示:
切勿使用同步API
数据从远程URL加载数据(内容:
——即使是在异步调度队列中也不例外,并且不要不经意地忽略try?
中的错误存在误解
URL
API
init(from decoder: Decoder) throws
只能在自定义结构中使用从给定的解码器
创建URL,非常类似于类相关的NSCoding
协议的init(coder
API)
在上下文中,要从字符串创建URL,必须使用
URL(string
URL(string: "http://json-schema.org/example/geo.json")!
这正是错误消息所说的:我期待一个解码器
,但我得到一个字符串
重要提示: 永远不要使用同步API
数据从远程URL加载数据(内容:
——即使是在异步调度队列中也不要加载数据,try?