Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In a view, how can I change the view's variables every time I press a button, using a struct's function?

I have a problem while coding in content view. I don’t understand how can I use struct’s func in content view. I would like to get helps from you guys. I get an error like this "Result of call to ‘changeText(text:)’ is unused".

Here’s simple example of what I’m trying to achieve,

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: {
            tmpTwo.changeText(text: tmp )
          }, label: {
            Text(tmp)
          })

        }
        .padding()
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
    }
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading