How to reference a generic Decodable struct in Swift 4

前端 未结 1 1630
暗喜
暗喜 2021-02-06 00:26

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 \"MyDecodabl

1条回答
  •  -上瘾入骨i
    2021-02-06 00:45

    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: Decodable {
        let items: [Element]
    }
    static func getResults(url: String, parameters: Parameters?, myStruct: Element.Type) {
        //...
            // On success REST response
            if response.result.isSuccess {
    
                do {
                    let jsonResults = try JSONDecoder().decode(Results.self, from: response.data!)
                    //success
                    print(jsonResults)
                } catch {
                    //Better not dispose errors silently
                    print(error)
                }
            }
        //...
    }
    

    Swift says types cannot be nested in generic context, so I moved it out to the outer non-generic context.

    Call it as:

    getResults(url: "url", parameters: nil, myStruct: MyDecodableStruct.self)
    

    0 讨论(0)
提交回复
热议问题