Swift 4.0中使用CodingKeys枚举忽略UIImage属性遇协议兼容问题
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
Codableand 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

