How to make generic store for Codable in Swift

Issue #465

Use EasyStash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import EasyStash

final class Store<T: Codable & ItemProtocol>: Codable {
var items = [T]()

func bookmark(item: T) {
items.append(item)
}

func unbookmark(item: T) {
guard let index = items.firstIndex(where: { $0.itemId == item.itemId }) else {
return
}

items.remove(at: index)
}

func isBookmark(item: T) -> Bool {
return items.contains(where: { $0.itemId == item.itemId })
}
}
1
2
3
4
5
6
7
8
9
10
11
12
import EasyStash

final class StoreContainer {
var food: Store<Food>

static var shared = StoreContainer()
let storage = try! Storage(options: Options())

init() {
food = try? storage.load(forKey: "food", as: Store<Food>.self) ?? Store<Food>()
}
}

If Swift has problem compiling because of generic, use try catch to declare in multiple steps in stead of ??

1
2
3
4
5
6
7
init() {
do {
self.food = try storage.load(forKey: "food", as: Store<Food>.self)
} catch {
self.food = Store<Food>()
}
}

Comments