You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
LeStorage/LeStorage/StoredSingleton.swift

47 lines
1.3 KiB

//
// StoredObject.swift
// LeStorage
//
// Created by Laurent Morvillier on 03/05/2024.
//
import Foundation
/// A class extending the capabilities of StoredCollection but supposedly manages only one item
public class StoredSingleton<T: SyncedStorable>: SyncedCollection<T> {
/// Sets the singleton to the collection without synchronizing it
public func setItemNoSync(_ instance: T) {
self.setSingletonNoSync(instance: instance)
}
/// updates the existing singleton
public func update() {
if let item = self.item() {
self.addOrUpdate(instance: item)
}
}
/// Returns the singleton
public func item() -> T? {
return self.items.first
}
public func tryPutBeforeUpdating(_ instance: T) async throws {
let result = try await StoreCenter.main.service().rawPut(instance)
if let item = self.item() {
item.copy(from: result)
}
}
// MARK: - Protects from use
public override func addOrUpdate(contentOfs sequence: any Sequence<T>) {
fatalError("method unavailable for StoredSingleton, use update")
}
func addOrUpdateIfNewer(_ instance: T) {
fatalError("method unavailable for StoredSingleton, use update")
}
}