Swift中结构体遵循Decodable协议实例化失败问题及解决
Swift泛型Resource结构体初始化错误修复
已定义的类型代码
Category结构体
struct Category: Codable, Hashable { let id: Int let name: String let image: String }
HttpMethod枚举
enum HttpMethod { case get([URLQueryItem]) case post(Data?) case delete var name: String { switch self { case .get: return "GET" case .post: return "POST" case .delete: return "DELETE" } } }
初始版本的Resource泛型结构体
struct Resource<T: Codable> { let url: URL var headers: [String: String] = [:] var method: HttpMethod = .get([]) let modelType: T }
初始化失败场景
执行以下代码创建Resource实例时触发编译错误:
let resource = Resource(url: URL.allCategories, modelType: Category.self)
错误提示:Type 'Category.Type' cannot conform to 'Decodable'
问题原因与修复方案
错误源于modelType声明的类型为T,但传入的Category.self是元类型Category.Type,两者类型不匹配。只需将modelType的类型修改为T.Type,即可解决该类型一致性问题。
修改后的Resource结构体代码
struct Resource<T: Codable> { let url: URL var headers: [String: String] = [:] var method: HttpMethod = .get([]) let modelType: T.Type }
内容的提问来源于stack exchange,提问作者john doe
相关产品推荐
相关产品推荐

