babbuki
babbuki

Reputation: 21

Swift function that return -> String and change var in class

I have a func writeSomethingInTextField(textfield: String) -> String, should change a value of var in class, but it doesn't, change var only temporary in func. Anyone know where is the problem?

class OperationsManagment {

    var TextField: String = ""
    func writeSomethingInTextField(textfield: String) -> String {
        if textfield == "" {
            
            print("you have to write something here")
            return "nil"
        }else {
           
            self.TextField = textfield
            return self.TextField

        }
    }

    func sendTextField() {
            print("\(TextField)")
      }
     
}

OperationsManagment().writeSomethingInTextField(textfield: "exampleText")


OperationsManagment().sendtextField()

Upvotes: 0

Views: 349

Answers (1)

John Montgomery
John Montgomery

Reputation: 7096

When you do OperationsManagment(), you're creating a new instance of the class but you aren't saving that instance anywhere. Then when you do it a second time, you're creating a second instance so anything you did to the first one doesn't apply to it. Instead you need to assign it to a variable so you can use the same instance both times:

let foo = OperationsManagment()
foo.writeSomethingInTextField(textfield: "exampleText")
foo.sendtextField()

Upvotes: 1

Related Questions