How to handle Generics in Environment Clients? #1069
Unanswered
cheeseonhead
asked this question in
Q&A
Replies: 2 comments 1 reply
-
Just recently had the same question come up for me to do with read/write to a keychain client. I think existential types could have a role here but they are not yet developed enough. Example: struct Storage {
var save: (any Encodable)
var load: (any Decodable) -> Data
} Although, still unsure about the load return value. This would propagate deciding the return type. |
Beta Was this translation helpful? Give feedback.
0 replies
-
You can represent your storage client as dealing with plain public struct StorageClient {
var _save: (String, Data) -> Void
var _load: (String) -> Data
public func save<T: Encodable>(key: String, value: T) throws {
self._save(key, try JSONEncoder().encode(value))
}
public func load<T: Decodable>(key: String, as type: T.Type) throws -> T {
try JSONDecoder().decode(T.self, from: self._load(key))
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Normally if I was building a generic storage wrapper, I might have something like this:
But for Clients in the Environment, we have seen approaches of converting the methods into function properties so their implementations can be dynamically created.
However, properties don't work with generics, so the following can't work:
I could lift the generic to the type itself:
But then that means in the domain code, in the Environment struct, I would need a StorageClient for each type I want to store:
Is there a better way to deal with this type of stuff?
Beta Was this translation helpful? Give feedback.
All reactions