Scope of variable in functions!

func check(name: String) {
var name = 56
print(name)
}

check(name: "something")

For the function mentioned above, I'm able to redeclare a variable with different datatype and if I try to print that variable, it prints 56 everytime. Can somebody explain me the why its allowing to redeclare the variable and how to access the variable with string datatype which is passed as parameter to the function.

It is because the name variable declared in the function shadows the parameter name.

This feature is called variable shadowing and Swift By Sundell has a nice quick tip about it.

1 Like

Is there any way to access the shadowed variable?

Not that I know of. As far as I know, variable shadowing is used specifically to disallow access to the shadowed variable.
However, you could use a do block to define a new scope and keep your shadowing variable restricted to that scope, like so:

func check(name: String) {
    do {
        let name = 56
        print(name) // Int: 56
    }
    print(name) // String
}
1 Like