如何在 Swift 4 中引用通用的可解码结构 [英] How to reference a generic Decodable struct in Swift 4
问题描述
我有一个函数,我想重用它并让它接受一个 Decocable 结构的参数.例如,这是我当前代码的简化(假设MyDecodableStruct"是在应用程序其他地方声明的可解码结构):
I have a function that I would like to reuse and have it accept a parameter of a Decocable struct. For example, this is a simplification of my current code (assume "MyDecodableStruct" is a Decodable struct declared elsewhere in the app):
static func getResults(url: String, parameters: Parameters) {
// On success REST response
if response.result.isSuccess {
struct Results: Decodable {
let items: [MyDecodableStruct]
}
if let jsonResults = try? JSONDecoder().decode(Results.self, from: response.data!) {
//success
}
}
而不是说MyDecodableStruct",我希望它是我作为参数传入的任何可解码结构.像这样:
and instead of saying "MyDecodableStruct", I would like it to be any Decodable struct I pass in as a parameter. Something like this:
static func getResults(url: String, parameters: Parameters, myStruct: Decodable) {
// On success REST response
if response.result.isSuccess {
struct Results: Decodable {
let items: [myStruct]
}
if let jsonResults = try? JSONDecoder().decode(Results.self, from: response.data!) {
//success
}
}
我会这样称呼它
getResults(url: "url", parameters: nil, myStruct: MyDecodableStruct)
我无法弄清楚如何让它工作的语法.我得到的错误是
I cannot figure out the syntax on how to get this to work though. The errors I get are
Type 'Results' does not conform to protocol 'Decodable'
Expected element type
关于处理这个问题的最佳方法有什么想法吗?
Any ideas on the best way to handle this?
推荐答案
当你想传递一个类型作为参数时,你需要将参数的类型声明为metatype.在您的情况下,它是一个需要符合 Decodable
的泛型类型.
When you want to pass a type as a parameter, you need to declare the type of the parameter as metatype. In your case, it's a generic type which needs to conform to Decodable
.
所以你可能需要这样写:
So you may need to write something like this:
struct Results<Element: Decodable>: Decodable {
let items: [Element]
}
static func getResults<Element: Decodable>(url: String, parameters: Parameters?, myStruct: Element.Type) {
//...
// On success REST response
if response.result.isSuccess {
do {
let jsonResults = try JSONDecoder().decode(Results<Element>.self, from: response.data!)
//success
print(jsonResults)
} catch {
//Better not dispose errors silently
print(error)
}
}
//...
}
Swift 说类型不能嵌套在泛型上下文中,所以我把它移到外部的非泛型上下文中.
Swift says types cannot be nested in generic context, so I moved it out to the outer non-generic context.
称之为:
getResults(url: "url", parameters: nil, myStruct: MyDecodableStruct.self)
这篇关于如何在 Swift 4 中引用通用的可解码结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!