Swift.RangeはCodableである、ではencodeフォーマットは? - がんばってなんか書く の続き
疑問
Swift.Range
をJSON encodeした結果は [a, b]
となることがわかった。
これはJSON Arrayを使って表現している。
では、[a, b, c]
な要素数3以上のArrayに対して、Range
のJSON decodeをかけるとどうなるだろうか?
環境
- Apple Swift version 5.7.2 (swiftlang-5.7.2.135.5 clang-1400.0.29.51)
- Xcode Version 14.2 (14C18)
- Playground
実験
インプットするJSONはこちら
{ "name":"0, 9, 10", "value":[ 0, 9, 10 ] }
JSONDecoder
で、decodeする。
JSON内のArrayをRangeでdecodeする
import Foundation let decoder = JSONDecoder() let json = """ { "name":"0, 9, 10", "value":[ 0, 9, 10 ] } """ do { struct Content: Codable { var name: String var value: Range<Int> } do { let data = json.data(using: .utf8) let content = try decoder.decode(Content.self, from: data!) print(content) } catch { print(error) } }
結果
Range(0..<9)
decoding errorとはならず、Arrayの第3要素目以降は無視して扱われることがわかった。
要素数が足りない場合は...
ちなみに、要素数が足りない場合には、ちゃんとエラーになる
{ "name":"0", "value":[ 0 ] }
valueNotFound(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "value", intValue: nil), _JSONKey(stringValue: "Index 1", intValue: 1)], debugDescription: "Unkeyed container is at end.", underlyingError: nil))