In Swift, you can use if let optional binding to unwrap an optional into a constant or variable with the same name:
func test()
{
let a: Int? = 1
if let a = a {
print("a = \(a)")
}
}
For everything inside the if let
statement, the optional a
is unwrapped into a regular int.
Likewise, I can use a guard statement to achieve a similar effect
func test()
{
let a: Int? = 1
guard let requiredA = a else{
return
}
print("a = \(requiredA)")
}
However, I can't use code like this: guard let a = a else
:
func test()
{
let a: Int? = 1
guard let a = a else{
return
}
print("a = \(a)")
}
Why not?
In a guard statement, if the conditional of the guard statement fails, the else clause is executed and you exit the current scope. If the conditional succeeds, a new variable/constant is created from guard statement's closing brace to the end of the current scope.
Why can't I do the same trick of mapping an optional into a variable/constant with the same name for remainder of the current scope?
P.S.: I realize this question isn't a perfect fit for this site. I'm open to suggestions as to where would be a better place for this question.
if
way creates two variables in different scopes, which is fine, while theguard
way would be creating two identically-named variables in the same scope, which would be a weird special case and complicate the variable resolution rules to allow it. I'm guessing, though; I don't know Swift. – user2357112 supports Monica