-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathPreferences.swift
More file actions
43 lines (33 loc) · 1.03 KB
/
Preferences.swift
File metadata and controls
43 lines (33 loc) · 1.03 KB
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
import Foundation
import JSONCodable
/// Preferences
open class Preferences<T : Codable>: Codable {
enum CodingKeys: String, CodingKey {
case data
}
/// Additional properties
public let data: T
init(
data: T
) {
self.data = data
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.data = try container.decode(T.self, forKey: .data)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(data, forKey: .data)
}
public func toMap() -> [String: Any] {
return [
"data": try! JSONEncoder().encode(data)
]
}
public static func from(map: [String: Any] ) -> Preferences {
return Preferences(
data: try! JSONDecoder().decode(T.self, from: JSONSerialization.data(withJSONObject: map["data"] as? [String: Any] ?? map, options: []))
)
}
}