-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
SingletonStorage.swift
56 lines (44 loc) · 1.82 KB
/
SingletonStorage.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
import CryptoKit
import Foundation
import Keychain
import Storage
/// `SingletonStorage` subclass of `DelegatedStorage` that uses a `SingletonStorageDelegate`.
open class SingletonStorage: DelegatedStorage {
/// `SingletonStorage` shared instance.
open class var standard: SingletonStorage { shared }
private static let shared = SingletonStorage()
/**
Create a `SingletonStorage`.
- Parameter delegate: `StorageDelegate`, defaults `SingletonStorageDelegate`.
- Parameter authenticationTag: Custom additional `Data` to be authenticated.
*/
public convenience init(_ delegate: StorageDelegate = SingletonStorageDelegate(),
authenticationTag: Data? = nil) {
self.init(delegate,
symmetricKey: SymmetricKey.generate(),
authenticationTag: authenticationTag)
}
}
/// `SingletonStorageDelegate` conforming `StorageDelegate` protocol.
open class SingletonStorageDelegate: StorageDelegate {
private var storage = [AnyHashable: Any]()
/// Create a `SingletonStorageDelegate`.
public init() {}
/**
Get `StorageData` for `StoreKey` from the keychain.
- Parameter key: `StoreKey` to store the `StorageData`.
- Returns: `StorageData` for `StoreKey`.
*/
open func data<D: StorageData>(forKey key: StoreKey) -> D? { storage[key] as? D }
/**
Set `StorageData` for `StoreKey` in the keychain.
- Parameter data: `StorageData` to store.
- Parameter key: `StoreKey` to store the `StorageData`.
*/
open func set(_ data: (some StorageData)?, forKey key: StoreKey) { storage[key] = data }
/**
Remove `StorageData` for `StoreKey` from the keychain.
- Parameter key: `StoreKey` to remove.
*/
open func remove(forKey key: StoreKey) { storage.removeValue(forKey: key) }
}