-
Notifications
You must be signed in to change notification settings - Fork 0
/
Item.swift
84 lines (74 loc) · 2.54 KB
/
Item.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import Foundation
class ItemDao : Codable {
var item: Item
init (item: Item){
self.item = item
}
convenience init?(json: String) {
guard let data = json.data(using: .utf8) else { return nil }
do {
let item = try JSONDecoder().decode(ItemDao.self, from: data)
self.init(item: item.item)
} catch {
print ("ItemDao Error Init: \(error)")
return nil
}
}
}
class Item : Codable, Identifiable {
var id: String
var isComplete: Bool = false
var summary: String
var ownerId: String
init(id: String = UUID().uuidString.lowercased(),
isComplete: Bool = false,
summary: String,
ownerId: String) {
self.id = id
self.isComplete = isComplete
self.summary = summary
self.ownerId = ownerId
}
// Initialize from JSON string
convenience init?(json: String) {
guard let data = json.data(using: .utf8) else { return nil }
do {
let item = try JSONDecoder().decode(Item.self, from: data)
self.init(id: item.id, isComplete: item.isComplete, summary: item.summary, ownerId: item.ownerId)
} catch {
return nil
}
}
// Custom decoding initializer
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.summary = try container.decode(String.self, forKey: .summary)
self.ownerId = try container.decode(String.self, forKey: .ownerId)
// Provide a default value for isComplete if it is missing
self.isComplete = try container.decodeIfPresent(Bool.self, forKey: .isComplete) ?? false
}
// Encoding function (no change needed)
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(isComplete, forKey: .isComplete)
try container.encode(summary, forKey: .summary)
try container.encode(ownerId, forKey: .ownerId)
}
enum CodingKeys: String, CodingKey {
case id
case isComplete
case summary
case ownerId
}
// Serialize to JSON string
func toJSON() -> String? {
do {
let data = try JSONEncoder().encode(self)
return String(data: data, encoding: .utf8)
} catch {
return nil
}
}
}