Search code examples
swiftui

How can I update a SwiftUI view's variable using a function from a struct?


While using SwiftUI, I'm trying to update a variable of a view using a function within a struct. Currently, my code is throwing this error: "Result of call to 'changeText(text:)' is unused." The relevant code is as follows:

import Foundation

public struct Brain {
    public func changeText(text: String) -> String {
        var text = text
        text = "Changed text!"
        return text
    }
}
import SwiftUI

struct ContentView: View {
    @State var tmp: String = "hello"
    var tmpTwo: Brain = Brain()

    var body: some View {
        VStack {
            Button(action: {
                tmp = tmpTwo.changeText(text: tmp)
            }, label: {
                Text(tmp)
            })
        }
        .padding()
    }
}

How can I resolve this error?

Thank you!


Solution

  • You need to use the return value of the function like so:

    
    import SwiftUI
    
    struct ContentView: View {
      @State var tmp: String = "hello"
      var tmpTwo: Brain = Brain()
        var body: some View {
            VStack {
              Button(action: {
                tmp = tmpTwo.changeText(text: tmp )
              }, label: {
                Text(tmp)
              })
            }
            .padding()
        }
    }