-
Notifications
You must be signed in to change notification settings - Fork 77
/
MemoryModel.swift
97 lines (83 loc) · 2.58 KB
/
MemoryModel.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
85
86
87
88
89
90
91
92
93
94
95
96
97
public class MemoryModel: HTMLRenderable, JSONRenderable, Equatable {
static var id = 1
public static var all = [MemoryModel]()
public var attributes = [String: Any]()
public var id: Int {
get {
return attributes["id"] as! Int
}
set(newID) {
attributes["id"] = newID
}
}
required public init(_ attributes: [String: Any]) {
self.attributes = attributes
self.attributes["id"] = self.dynamicType.id
self.dynamicType.id += 1
}
public subscript(name: String) -> Any? {
get {
return attributes[name]
}
set(newValue) {
attributes[name] = newValue
}
}
public static func create(attributes: [String: String]) -> Self {
let resolvedAttributes = self.resolveAttributes(attributes)
let new = self.init(resolvedAttributes)
all.append(new)
return new
}
public static func find(id: String?) -> MemoryModel? {
guard let stringID = id else { return nil }
guard let intID = Int(stringID) else { return nil }
return find(intID)
}
public static func find(id: Int?) -> MemoryModel? {
return all.filter { $0.id == id }.first
}
public static func destroy(model: MemoryModel?) {
if let m = model {
all = all.filter({ $0.id != m.id })
}
}
public static func allAttributes() -> Any {
var items = [Any]()
for model in all {
var attrs = model.attributes
attrs["id"] = String(model.id)
items.append(attrs as Any)
}
return items as Any
}
public static func reset() {
all = [MemoryModel]()
id = 1
}
public func update(attributes: [String: String]) {
self.attributes = MemoryModel.resolveAttributes(attributes)
}
static func resolveAttributes(attributes: [String: String]) -> [String: Any] {
var attrs = [String: Any]()
for (key, value) in attributes {
if let integer: Int = Int(value) {
attrs[key] = integer
} else if let double: Double = Double(value) {
attrs[key] = double
} else {
attrs[key] = value
}
}
return attrs
}
public func renderableAttributes() -> [String: Any] {
return self.attributes
}
public func renderableJSONAttributes() -> [String: Any] {
return self.attributes
}
}
public func == (lhs: MemoryModel, rhs: MemoryModel) -> Bool {
return lhs.id == rhs.id
}