0
@State var myDict: [String: Double] = [:]

var body: some View {
    HStack(alignment: .top) {
        Button(action: {
            self.myDict[self.tag ?? ""] = amountValue
        }) 
    }
}

I have two user, when i select 1st user I add value to myDict, and when I select 2nd user I want to add another value to it (means myDict will have 2 object), but when i select 2nd user @state variable is refresh and have only one value of 2nd user. (means myDict have 1 object)

is there any way so that I can have both the value in dict not only one?

7
  • are the dict ket OK ? do these correspond to the self.tag ? Commented Feb 28, 2022 at 16:38
  • yes its correct key is unique (self.tag) Commented Feb 28, 2022 at 16:47
  • So each user as each own tag ? how is the relation between user, button and tag ? From the code you gave we only see one button with one dict and one button that set always the same entry in the dictionary. Commented Feb 28, 2022 at 16:51
  • yes each user has its own tag, so when diff user selected i want to create dictionary if there unique tag and value..and want to do some calculations on that Commented Feb 28, 2022 at 16:55
  • May be I am wrong but you seems to have a view that is recreated each time a user is selected . is it not ? If a view is recreated, all its variables are recreated (you can check with onAppear). May be I am wrong but your dictionary should in upper place in your view hierarchy. Commented Feb 28, 2022 at 17:00

2 Answers 2

2

actually, this can happen that for both users self.tag is nil and ("") is used as a key for the dictionary

self.myDict[self.tag ?? ""] = amountValue

and if this happens you may want to make sure that self.tag is not nil

I have created a test environment just like your case but I have

import SwiftUI

struct swiftUIDoubt1: View {
    

    @State var myDict: [String: Double] = [:]
    
    var body: some View {
        VStack{
            Button(action: {
                myDict["Hello, World!"] = 9.99999
                print(myDict)
            }, label: {
                Text("\(myDict["Hello, World!"] ?? 0)")
                    .padding()
            })
            
            Button(action: {
                myDict["bye, World!"] = 1.11111
                print(myDict)
            }, label: {
                Text("\(myDict["bye, World!"] ?? 0)")
                    .padding()
            })
            
        }
        .onAppear(perform: {
            print(myDict)
        })
    }
}

now as you can see when my screen will appear my dictionary should be empty and an empty dictionary must be printed, as you can see in the image console log when the app is first opened

console log when app is first opened

device screen when app is first opened

when I click first button single item will be added and you can see in console log single item added

and when I will click on the second button you can see I have two different items in my dictionary

two items are added

let success = "two different items has been added to dictionary"

as @state variable to managed by swift UI and will not change with ui update

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for help..but in this case view is not refreshing ..so when there is some variable change..whole view will update and in that case both dictionaries will be empty again....because my view is recreating when diff user selected
In my experience, you can do two things first you may have missed State before the dictionary or you can create a singleton class conform to "Observable" add your dictionary as "@Published" property item and then watch that from your class, with "@Observed" property it will be different from your Swift UI struct, and recreate will not destroy that file
0

Small example : The add in the subview update the dictionnaire for the desired user in parent view

import SwiftUI

struct UpdateUsersDict: View {
    @State var myDict: [String: Double] = [:]
    @State var amount: Double = 100
    var body: some View {
        VStack {
            HStack {
                OneUserView(myDict: $myDict, amount: amount, tag: "user 1")
                OneUserView(myDict: $myDict, amount: amount, tag: "user 2")
                OneUserView(myDict: $myDict, amount: amount, tag: "user 3")
            }
            HStack {
                Text("\(myDict["user 1"] ?? -1)")
                Text("\(myDict["user 2"] ?? -1)")
                Text("\(myDict["user 3"] ?? -1)")
            }
        }
    }
}

struct OneUserView: View {
    @Binding var myDict: [String: Double]
    @State var amount: Double
    var tag: String

    var body: some View {
        HStack(alignment: .top) {
            Button(tag, action: {
                self.myDict[self.tag] = amount
            })
        }
    }
}

struct UpdateUserDict_Previews: PreviewProvider {
    static var previews: some View {
        UpdateUsersDict()
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.