secretive/Sources/Packages/Sources/SecretKit/SecretStoreList.swift

47 lines
1.4 KiB
Swift
Raw Normal View History

2020-03-09 03:03:40 +00:00
import Foundation
import Combine
/// A "Store Store," which holds a list of type-erased stores.
2020-03-09 03:03:40 +00:00
public class SecretStoreList: ObservableObject {
/// The Stores managed by the SecretStoreList.
2020-03-09 03:03:40 +00:00
@Published public var stores: [AnySecretStore] = []
/// A modifiable store, if one is available.
2020-03-09 03:03:40 +00:00
@Published public var modifiableStore: AnySecretStoreModifiable?
2020-05-16 06:19:00 +00:00
private var sinks: [AnyCancellable] = []
2020-03-09 03:03:40 +00:00
/// Initializes a SecretStoreList.
2020-03-09 03:03:40 +00:00
public init() {
}
/// Adds a non-type-erased SecretStore to the list.
2020-03-09 03:03:40 +00:00
public func add<SecretStoreType: SecretStore>(store: SecretStoreType) {
2020-03-09 03:44:15 +00:00
addInternal(store: AnySecretStore(store))
2020-03-09 03:03:40 +00:00
}
/// Adds a non-type-erased modifiable SecretStore.
2020-03-09 03:03:40 +00:00
public func add<SecretStoreType: SecretStoreModifiable>(store: SecretStoreType) {
let modifiable = AnySecretStoreModifiable(modifiable: store)
modifiableStore = modifiable
2020-03-09 03:44:15 +00:00
addInternal(store: modifiable)
}
/// A boolean describing whether there are any Stores available.
2020-03-21 03:20:20 +00:00
public var anyAvailable: Bool {
stores.reduce(false, { $0 || $1.isAvailable })
}
2020-03-09 04:11:59 +00:00
}
extension SecretStoreList {
2020-05-16 06:19:00 +00:00
private func addInternal(store: AnySecretStore) {
2020-03-09 03:44:15 +00:00
stores.append(store)
let sink = store.objectWillChange.sink {
self.objectWillChange.send()
}
sinks.append(sink)
2020-03-09 03:03:40 +00:00
}
}