编写一个函数来解码泛型 JSON。我如何给出 Codable.Protocol 的论据?
Writing a function to decode generic JSON. How do I give an argument for Codable.Protocol?
我正在尝试编写我的第一个严肃的 Xcode 项目,但我没有那么多 Swift 5 的经验。因此我什至不确定是否有什么想法很有道理。
我手头的项目涉及大量JSON 文件的获取和解码。响应有两种或三种模式。所以我想我会写一个 func
并将响应模式传递给它。
我使用 decode<T>(_ type: T.Type, from data: Data): JSONDecoder
来解码我的数据。此函数的第一个参数显然具有类型 T.Type
。但实际上应该是Codable.Protocol
类型。
有没有什么办法可以 Codable
得到它?
这是我的函数:
func requestPageContent(forCodable codable: Codable, completion: @escaping (Result<PageContent, Error>) -> Void) {
DispatchQueue.global(qos: .default).async {
if let jsonData = try? Data(contentsOf: self) {
if let requestResults = try? JSONDecoder().decode(type(of: codable).self, from: jsonData) {
DispatchQueue.main.async {
completion(.success(requestResults))
}
} else {
print("error: json decoder")
}
} else {
print("error: fetch data")
}
}
}
谢谢。
你的意思是 requestPageContent
是通用的,像这样:
func requestPageContent<Content: Codable>(forCodable codable: Content,
completion: @escaping (Result<Content, Error>) -> Void) {
...
if let requestResults = try? JSONDecoder().decode(Content.self, from: jsonData) {
...
这表示您正在请求某些 特定的 内容类型,在 compile-time.
中已知
我正在尝试编写我的第一个严肃的 Xcode 项目,但我没有那么多 Swift 5 的经验。因此我什至不确定是否有什么想法很有道理。
我手头的项目涉及大量JSON 文件的获取和解码。响应有两种或三种模式。所以我想我会写一个 func
并将响应模式传递给它。
我使用 decode<T>(_ type: T.Type, from data: Data): JSONDecoder
来解码我的数据。此函数的第一个参数显然具有类型 T.Type
。但实际上应该是Codable.Protocol
类型。
有没有什么办法可以 Codable
得到它?
这是我的函数:
func requestPageContent(forCodable codable: Codable, completion: @escaping (Result<PageContent, Error>) -> Void) {
DispatchQueue.global(qos: .default).async {
if let jsonData = try? Data(contentsOf: self) {
if let requestResults = try? JSONDecoder().decode(type(of: codable).self, from: jsonData) {
DispatchQueue.main.async {
completion(.success(requestResults))
}
} else {
print("error: json decoder")
}
} else {
print("error: fetch data")
}
}
}
谢谢。
你的意思是 requestPageContent
是通用的,像这样:
func requestPageContent<Content: Codable>(forCodable codable: Content,
completion: @escaping (Result<Content, Error>) -> Void) {
...
if let requestResults = try? JSONDecoder().decode(Content.self, from: jsonData) {
...
这表示您正在请求某些 特定的 内容类型,在 compile-time.
中已知