lundi 26 avril 2021

Swift: How can I successively change my variable in a if-else loop?

I'm all new to Swift since three days back and are currently trying to make a simple if-else loop, just to try it's functions, in which I want to change the value of the string that's supposed to be returned from my function like this:

class TestClass(){    
var TestString = "0"
    
    func TestFunc()->String {
        
        
        if (TestString == "0") {
            TestString = "5"
        }
        else if (TestString == "5") {
            TestString = "8"
        }
        else if (TestString == "8") {
            TestString = "12"
        }
        else if (TestString == "12") {
            TestString = "17"
        }
        else if (TestString == "17") {
            TestString = "25"
        }
       
        return TestString
    }
}

But when I test the method with this code from the InterfaceController:

@IBAction func test(){
        
        print(TestClass().TestFunc())
        
    }

The first time I tap the button it prints "5" as expected. But the second and third, and so on, time it keeps printing "5" even though I constantly updates the value of the TestString after each if/else if statement. It feels like the TestString doesn't update it's value or if it resets between every tap.

Does anyone sit on a great solution to this?

Aucun commentaire:

Enregistrer un commentaire