사용자 지정 유형을 JSON에 사용자 지정 방식으로 인코딩하는 것은 Swift 4에서 쉽게 수행 할 수 있으며 유용한 설명서가 있습니다. 그러나 Foundation
유형을 사용자 정의 방식으로 인코딩하는 데 문제가 있습니다. 유형 TimeInterval
의 특성을 가진 내 사용자 정의 유형은 다음과 같이 분, 초를 표시하는 JSON 형식으로 Codable
을 할 필요가 :맞춤 설정 방식으로 이미 코드 가능 (예 : TimeInterval)을 준수하는 기초 유형을 인코딩하는 방법은 무엇인가요?
// my type:
struct MyType: Codable {
let time: TimeInterval = 65.12
}
// required JSON representation:
"myType": {
"time":
{
"minutes": 1,
"seconds": 5.12
}
}
나는 각자에 대한 encode(to:)
및 init(decoder:)
의 사용자 지정 구현을 제공하는 경우는, 잘 작동 내 타입의. 하지만 나는 자신을 반복하지 않고 단순히 TimeInterval
에 대해 이러한 메서드의 사용자 지정 버전을 제공하고 싶습니다. 불행하게도이 코드가 호출되지 없구요
extension TimeInterval {
enum CodingKeys: String, CodingKey {
case minutes
case seconds
}
func encode(to encoder: Encoder) throws {
let minutes = (NSInteger(self)/60) % 60
let seconds = self.truncatingRemainder(dividingBy: 60)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(minutes, forKey: .minutes)
try container.encode(seconds, forKey: .seconds)
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
guard let minutes = try? values.decode(Int.self, forKey: .minutes), let seconds = try? values.decode(Double.self, forKey: .seconds) else {
throw NSError()
}
self = TimeInterval(Double(minutes) * 60.0 + seconds)
}
}
:하십시오 TimeInterval
값은 항상 밖으로 상자의 Codable
을 준수하는 Double
을 인코딩의 기본 구현을 사용하는 것 같다 인코딩 그래서 이런 확장을 시도했다.
let myType = MyType(time: 65.12)
let encoded = try! JSONEncoder().encode(myType)
let json = String(data: encoded, encoding: .utf8)!
print(json)
// prints:
// "myType":
// {
// "time": 65.12
// }
어떻게 해결할 수 있습니까?
편집 : 필자는 첫 번째 문장에서 쓴 것처럼 솔루션을 찾고 있지 않으며 내 사용자 지정 형식을 인코딩하는 방법을 찾고 있지 않습니다. 이것은 이미 내 코드에서 잘 작동합니다. 변경하려고 Foundation 형식 TimeInterval
의 인코딩 동작을 변경하려고합니다.
고마워요! 내가 이해하는 한, 내 유형의 TimeInterval 특성을 'Time'사용자 정의 유형으로 대체하고 필요한 특성 및 이름을 사용하는 것이 좋습니다. 아마 좋은 해결 방법 일 겁니다. 하지만 TimeInterval에서 encode (to :) 및 init (from :)을 재정의 할 수 없다는 데 동의합니까? 그게 기능 이냐 버그 야? 그것에 관한 문서가 있습니까? – Goodsquirrel
코드화 가능 구조에서 encode 메서드를 구현해야합니다. TimeInterval (Double)에서 구현하지 마십시오. –