You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 19:00:06