Shared/Models/Response.swift (3334B)
1import Foundation
2
3
4struct Response: Codable, Hashable, Sendable {
5 var questionID: String
6
7 var prompt: String
8
9 var value: ResponseValue?
10}
11
12
13
14enum ResponseValue: Hashable, Sendable {
15 case options([String])
16
17
18
19 case tokens([String])
20 case number(Decimal)
21 case text(String)
22 case place(PlaceAnswer)
23}
24
25extension Response {
26
27 var tokenIDs: [String] {
28 switch value {
29 case .tokens(let ids): ids
30 case .place(let place): [place.tokenID]
31 case .options, .number, .text, nil: []
32 }
33 }
34}
35
36extension ResponseValue {
37
38
39 static let yesOption = "Yes"
40 static let noOption = "No"
41}
42
43extension ResponseValue: Codable {
44 private enum CodingKeys: String, CodingKey {
45 case options
46 case tokens
47 case number
48 case text
49 case place
50 }
51
52 init(from decoder: Decoder) throws {
53 let container = try decoder.container(keyedBy: CodingKeys.self)
54 guard container.allKeys.count == 1, let key = container.allKeys.first else {
55 throw DecodingError.dataCorrupted(
56 DecodingError.Context(
57 codingPath: container.codingPath,
58 debugDescription: "Expected exactly one response value key"
59 )
60 )
61 }
62 switch key {
63 case .options: self = .options(try container.decode([String].self, forKey: key))
64 case .tokens: self = .tokens(try container.decode([String].self, forKey: key))
65 case .number: self = .number(try container.decode(Decimal.self, forKey: key))
66 case .text: self = .text(try container.decode(String.self, forKey: key))
67 case .place: self = .place(try container.decode(PlaceAnswer.self, forKey: key))
68 }
69 }
70
71 func encode(to encoder: Encoder) throws {
72 var container = encoder.container(keyedBy: CodingKeys.self)
73 switch self {
74 case .options(let options): try container.encode(options, forKey: .options)
75 case .tokens(let tokens): try container.encode(tokens, forKey: .tokens)
76 case .number(let number): try container.encode(number, forKey: .number)
77 case .text(let text): try container.encode(text, forKey: .text)
78 case .place(let place): try container.encode(place, forKey: .place)
79 }
80 }
81}
82
83
84
85struct PlaceAnswer: Codable, Hashable, Sendable {
86 var tokenID: String
87 var coordinate: Coordinate?
88
89 var accuracy: Double?
90}
91
92struct Coordinate: Codable, Hashable, Sendable {
93 var latitude: Double
94 var longitude: Double
95}