0

How can I initialize or update value of a variable, like with UIKit, in SwiftUI?

For example in the code below I can update my value with action of a Button or with .onAppear() of Text, and there is some other ways. But I am interested if there is a way or tech for coding like this:

struct ContentView: View {
    
    @State private var valueOfA: String?
    
    var body: some View {
        valueOfA = "Magic!" // ← Here(I know it is impossible but if there is a way of this coding?)
        
        Button("change") { valueOfA = "omid" }
        
        Button("nil") { valueOfA = nil }
        
        Text(valueOfA ?? "")
            .onAppear {
                valueOfA = "Some Value"
            }
    }
}
5
  • 3
    What do you want to achieve? What is your goal? Commented Nov 8, 2020 at 0:06
  • 2
    The problem here is that you are changing a @State variable in the body. This will cause an infinite loop of the view trying to update itself. What do you want instead? Commented Nov 8, 2020 at 0:07
  • What do you want to achieve? Good Question! Some times we are using GeometryReader for some reason I wanted update my values without using .onAppear or .onChange(), because "value in" is not reachable out side of GeometryReader, and other part of program need those data, I thought if we code just update those like UIKit mode Commented Nov 8, 2020 at 0:12
  • 2
    It might help if you create an actual example with GeometryReader so we can see the big picture here. Commented Nov 8, 2020 at 0:25
  • @pawello2222: my Goal is currently to find Answer of Question, what ever if we can find or not, I want be sure about the possibility of initialize or update value of a variable, like with UIKit, in SwiftUI? debugging of this project is not important for me. As you said I wanted give a pic Commented Nov 8, 2020 at 3:33

1 Answer 1

2

Well... it is really like with Alice...

demo

One has got into mind... probably you wanted this:

struct ContentView: View {
    
    @State private var valueOfA: String?
    
    var body: some View {
        let valueOfA = self.valueOfA ?? "Magic!"
        
        Button("change") { self.valueOfA = "omid" }
        
        Button("nil") { self.valueOfA = nil }
        
        Text(valueOfA)
            .onAppear {
                self.valueOfA = "Some Value"
            }
    }
}

... and by the way we do not change frame in draw(_ rect:) in UIKit, yes?, but you try to do similar to that.

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

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.