Cannot change value from another struct/another file from SwiftUI

Hi all,

I just started with Swift and SwiftUI and after few hours I'm a bit confused about how structs are working. Can someone point me to the right direction? This is what I'm trying to do:

  • I have a simple SwiftUI file:
import SwiftUI

struct MyFirstPackage: View {
 
    @State var run = MyFirstPackageModelStruct(name: "myName")
    
    var body: some View {
        HStack{
            Text(run.name) // I can see "myName"
            HStack{
                Button("change") { // I see button Button "change"
                    run.name = "TEXT" // now I'm trying to change "name" to something else
                    run.set(text: "TEXT2") // trying to change it using method
                    print(run.name) // I still see "myName"
                    print(run.get()) // I still see "myName"
                }
            }
        }
    }    
}

struct MyFirstPackage_Previews: PreviewProvider {
    static var previews: some View {
        MyFirstPackage()
    }
}

And this is my MyFirstPackageModel file:

import Foundation

struct MyFirstPackageModelStruct {
    
    var name: String
    
    func get() -> String {
        return name
    }
    
    mutating func set(text: String) {
        name = text
    }
}

Maybe it's not possible with struct and I need to change my model file to class?

Thanks!

Terms of Service

Privacy Policy

Cookie Policy