-1

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"
Marmelador
  • 947
  • 7
  • 27
  • 2
    You said *"If it's true, the current scope continued in execution."* and that is correct. `name == "Hans"` *is* true, so the execution continues and the else-clause is not executed. The behaviour is exactly as you described it. – Martin R Jul 12 '17 at 20:02
  • 2
    If the semantics of `guard` are confusing, you can replace it in your mind with "ensure" or "assert" or "make sure that." That's how you should read it. This must be true to continue this scope. – Rob Napier Jul 12 '17 at 20:05
  • continuing what Rob said: "but if it's not what we expected it to be, then follow the *else* statement and exit scope" To let it make more sense change `print("It's Hans")` **to** `print("It's NOT Hans")` – mfaani Jul 12 '17 at 20:11

1 Answers1

7

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

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