swift-composable-architecture icon indicating copy to clipboard operation
swift-composable-architecture copied to clipboard

Add default providing persistence key

Open lukeredpath opened this issue 1 year ago • 3 comments

Adds a special DefaultProvidingKey which acts as a decorator around another persistence key and holds on to a default value.

This allows you to define the default value for a particular key alongside the key definition and not need to declare a default value everywhere you use @Shared or @SharedReader with that key.

For example:

extension User {
  static let placeholder = User(id: UUID(0), name: "")
}

extension PersistenceKey where Self == DefaultValueProviding<InMemoryKey<User>> {
    static var user: Self {
        inMemory("user", defaultValue: .placeholder)
    }
}

@Reducer
struct LoggedIn {
  struct State: Equatable {
    @SharedReader(.user) var user
  }
}

This PR provides overloads for creating inMemory and fileStorage keys with a default value. I have not provided any overloads for appStorage keys as there are quite a lot of them already, but they could also be added if desired.

One caveat to this implementation is that because keys are required to be hashable, the default value must also be a hashable type.

Previous discussion: https://github.com/pointfreeco/swift-composable-architecture/discussions/2956

lukeredpath avatar Apr 10 '24 23:04 lukeredpath

WHOA that's cool! Hope it gets Stephen and Brandon's blessing 🙂

acosmicflamingo avatar Apr 10 '24 23:04 acosmicflamingo

I would love to have this capability. I see the value in modeling the API after what SwiftUI does, but this seems like a reasonable alternative for those who want to keep it DRY.

hiltonc avatar Apr 11 '24 20:04 hiltonc

Hey @lukeredpath, just wanted to let you know we haven't forgotten about this. We've made a few small changes and hope to merge it tomorrow, but we may make a few more tweaks before then too.

mbrandonw avatar Apr 16 '24 00:04 mbrandonw

Congrats @lukeredpath !

acosmicflamingo avatar Apr 16 '24 18:04 acosmicflamingo