Search code examples
swiftguardcontrol-flow

Guard does not exit function


This might be a very stupid question but bear with me: To my understanding and after reading the documentation and various examples on other websites, a guard statement checks a bool. If it's true, the current scope continued in execution. If not, it's else clause is executed. Here one should use a return statement to exit the current scope. However this does not work for me.

Basically: Why does return not exit out of this function?

class Person {

    var name: String

    init (name: String) {
        self.name = name
    }

    func reverseNameUnlessItsHans() {
        guard name == "Hans" else { //should exit the scope...
            print("It's Hans")
            return
        }
        self.name = String(name.characters.reversed()) //...yet this is executed
    }
}

var myPerson = Person(name: "Hans")
myPerson.reverseNameUnlessItsHans()
print(myPerson.name) //prints "snaH"

Solution

  • You are guarding AGAINST the case where name == "Hans"

    Change your reverse to be inside the guard, and the print should replace the reverse