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.
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
}