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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…