TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Encapsulation by EnvironmentKey ?

Forums > SwiftUI

Hello,I want to encapsulate part of the properties from the store. I thought it might be possible to create an Environment Key for different properties I am trying to get a token from the store using EnvironmentKey, but the token by the EnvironmentKey unchanged. However, if I use EnvironmentKey of the store, it works.

import SwiftUI

@Observable
final class Store: TokenServiceProtocol {
    var token: Token?

    func saveToken(token: Token) {
        self.token = token
    }
  ...
}

struct StoreKey: EnvironmentKey {
    static let defaultValue: Store = Store()
}

extension EnvironmentValues {
    var store: Store {
        get { self[StoreKey.self] }
        set { self[StoreKey.self] = newValue }
    }
}

extension EnvironmentValues {
    var token: Token? {
        get { self.store.token }

        set { self.store.token = newValue }
    }
}
struct ContentView: View {
    @Environment (\.token) private var token: Token?
    @Environment (\.store) private var store
    var body: some View {
        NavigationStack {
            VStack{
                Button("Save token") {
                    tokenInteractor.saveToken(id: t)
          // token from  EnvironmentKey  token not updated
                    print(token?.Id ?? "token is void") 
          // token from EnvironmentKey store.token work good
                    print(store.token?.id ?? "store.token is void")
                }
    }
}

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.