Back in November of 2016 I posted a question asking why I couldn\'t use guard to create an unwrapped version of a variable using the same name as the optional, like you can
TL;DR
guard let foo = foo
is legal if foo
was defined in another scope.
The example from your linked question:
func test()
{
let a: Int? = 1
guard let a = a else{
return
}
print("a = \(a)")
}
still doesn't work because the guard
statement is trying to create another variable a
in the same scope.
This example:
//Test of using guard to create an unwrapped version of a var, like if let
func guardTest(_ viewController: UIViewController?) -> UIViewController? {
// Check if the current viewController exists
print(String(describing: viewController))
guard let viewController = viewController else {
return nil
}
print(String(describing: viewController))
return viewController
}
works for the same reason that this does:
func test(a: Int)
{
print(type(of: a)) // Int
let a = 3.14
print(type(of: a)) // Double
}
The parameter to the function is defined in a different scope, so Swift allows you to create a local variable with the same name.