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

Swift 4.0中使用CodingKeys枚举忽略UIImage属性遇协议兼容问题

Fixing "Does not conform to Decodable" Error for Your Thumbnail Struct

Hey, I get why this is confusing—you’ve explicitly used CodingKeys to exclude the image property from decoding, yet Xcode still throws a "does not conform to Decodable" error. Let’s break down the fixes and why this might be happening:

1. Manually Implement the Decoder Initializer

The most reliable fix here is to skip Swift’s auto-synthesized Decodable implementation and write the init(from:) method yourself. This removes any ambiguity for the compiler about which properties to handle during decoding:

import UIKit
struct Thumbnail: Codable {
    let url: String
    let width: UInt
    let height: UInt
    var image: UIImage?
    
    enum CodingKeys: String, CodingKey {
        case url, width, height
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        // Decode only the properties defined in CodingKeys
        url = try container.decode(String.self, forKey: .url)
        width = try container.decode(UInt.self, forKey: .width)
        height = try container.decode(UInt.self, forKey: .height)
        // We don’t touch the `image` property here—it’s for local caching only
    }
}

2. Check for Xcode Quirks

Sometimes the issue is just a Xcode caching glitch or a bug in older versions. Try these quick fixes first:

  • Clean your project build folder with Cmd + Shift + K
  • Restart Xcode entirely
  • If you’re on an older Xcode version, consider updating to the latest stable release (some older versions had edge-case bugs with Codable and optional non-conforming properties)

Why This Happens

Even though CodingKeys should tell the compiler to ignore image, Swift’s auto-synthesis for Codable can sometimes still check all stored properties for conformity—especially when dealing with mutable optional properties that don’t conform. By writing the decoder initializer manually, you take full control and eliminate that check entirely.

内容的提问来源于stack exchange,提问作者Doug

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:00:04