UserDefaultsStore
open class UserDefaultsStore<T> where T : Identifiable, T : Decodable, T : Encodable
UserDefaultsStore
offers a convenient way to store a collection of Codable
objects in UserDefaults
.
-
Store’s unique identifier.
Warning: Never use the same identifier for two -or more- different stores.
Declaration
Swift
public let uniqueIdentifier: String
-
JSON encoder. default is JSONEncoder()
Declaration
Swift
open var encoder: JSONEncoder
-
JSON decoder. default is JSONDecoder()
Declaration
Swift
open var decoder: JSONDecoder
-
Initialize store with given identifier.
Warning: Never use the same identifier for two -or more- different stores.
Declaration
Swift
required public init?(uniqueIdentifier: String, useHashing: Bool = false)
Parameters
uniqueIdentifier
uniqueIdentifier: store’s unique identifier.
useHashing
Whether keys should be hashed before storing or not. default is false
-
Save object to store.
Throws
JSON encoding error.Declaration
Swift
public func save(_ object: T) throws
Parameters
object
object to save.
-
Save optional object (if not nil) to store.
Throws
JSON encoding error.Declaration
Swift
public func save(_ optionalObject: T?) throws
Parameters
optionalObject
optional object to save.
-
Save array of objects to store.
Throws
JSON encoding error.Declaration
Swift
public func save(_ objects: [T]) throws
Parameters
objects
object to save.
-
Get object from store by its id.
Declaration
Swift
public func object(withId id: T.ID) -> T?
Parameters
id
object id.
Return Value
optional object.
-
Get array of objects from store for a given array of id values.
Declaration
Swift
public func objects(withIds ids: [T.ID]) -> [T]
Parameters
ids
array of ids.
Return Value
array of objects with the given ids.
-
Get all objects from store.
Declaration
Swift
public func allObjects() -> [T]
Return Value
array of all objects in store.
-
Delete object by its id from store.
Declaration
Swift
public func delete(withId id: T.ID)
Parameters
id
object id.
-
Delete objects with ids from given ids array.
Declaration
Swift
public func delete(withIds ids: [T.ID])
Parameters
ids
array of ids.
-
Delete all objects in store.
Declaration
Swift
public func deleteAll()
-
Count of all objects in store.
Declaration
Swift
public var objectsCount: Int { get }
-
Check if store has object with given id.
Declaration
Swift
public func hasObject(withId id: T.ID) -> Bool
Parameters
id
object id to check for.
Return Value
true if the store has an object with the given id.
-
Iterate over all objects in store.
Declaration
Swift
public func forEach(_ object: (T) -> Void)
Parameters
object
iteration block.