0
[String: Any]?
유형의 선택적 metaData 필드가있는 구조체가 있습니다. 해당 구조체에 대한 JSON을 구문 분석하고 명시 적으로 사전을 매핑하지 않고 그대로 유지하고 싶습니다.Swift 4에서 실제 매핑없이 선택적 사전을 디코딩
struct MyObject: Decodable {
let id: String
let whatever: String
let metaData: [String: Any]?
enum CardKeys: String, CodingKey {
case id
case whatever
case metaData
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CardKeys.self)
id = try container.decode(String.self, forKey: .id)
whatever = try container.decode(String.self, forKey: .whatever)
metaData = try container.decodeIfPresent([String: Any].self, forKey: .metaData)
}
}
코드가 컴파일되고 시작되지만 실행시 실패합니다. 나는 [String: Any]
이 내가 여기서 사용할 수있는 유효한 유형이 아니라고 생각합니다. 하지만 어떻게 그럴 수 있죠?
관련과 [? 스위프트 복호 프로토콜 중첩 된 JSON 구조체를 디코딩하는 방법 (https : //로 유래. com/questions/44549310/how-to-decode-a-nested-json-struct-with-swift-decodable-protocol)에 설명되어 있습니다. –
'복호화 가능'은 동적 키를 염두에두고 설계되지 않았습니다. 이 문제를 해결할 수는 있지만 더 나은 접근법은 모든 가능한 메타 데이터를 옵션 속성으로 갖는 MyMetadata 구조체를 정의하는 것입니다 –