Memory

public actor Memory<T> : Storage where T : Decodable, T : Encodable, T : Sendable

A storage actor for storing objects in memory.

Memory<T> provides thread-safe in-memory storage using Swift’s actor isolation. It’s used as the underlying storage for MemoryStorage but can also be used directly when you need fine-grained control over storage operations.

Thread Safety

As an actor, Memory<T> ensures all storage operations are thread-safe by serializing access. Multiple concurrent tasks can safely call storage methods without external synchronization.

Persistence

Data stored in Memory<T> exists only in RAM and is lost when the app terminates. For persistent storage, use Keychain<T> or other storage implementations.

Example Usage

let memory = Memory<User>()

// Save a user
try await memory.save(item: currentUser)

// Retrieve the user
if let user = try await memory.get() {
    print("Found user: \(user.name)")
}

// Delete the user
try await memory.delete()

Parameters

T

The type of the object to be stored. Must conform to Codable for serialization and Sendable for safe concurrent access.

  • save(item:) Asynchronous

    Saves the given item in memory.

    Declaration

    Swift

    public func save(item: T) async throws

    Parameters

    item

    The item to save.

  • get() Asynchronous

    Retrieves the item from memory.

    Declaration

    Swift

    public func get() async throws -> T?

    Return Value

    The item if it exists, nil otherwise.

  • delete() Asynchronous

    Deletes the item from memory.

    Declaration

    Swift

    public func delete() async throws