Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJose Patarroyo
2,953 PointsHello, In the video he uses the same constant name in and out of the function and he doesn't get an error. Why?
IN the video he uses the same constant name inside and outside the function and the code runs with no errors. Does it mean that the variables and constants inside functions are completely independent from the rest of the code?
1 Answer
Martin Wildfeuer
Courses Plus Student 11,071 PointsLet me try to explain:
- Variables defined outside a function are accessible within a function.
- Variables defined within a function are only accessible within the scope of this function.
- Variables defined within a function are not accessible by other functions.
- You can still pass variables between functions as a parameter. (Passed by value, changes will not affect the original variable, though)
- Also have a look at "inout" at Apple Docs
// Defined "global" and available
// in all functions
let test = "Test"
func testing() {
// test is only accessible within this function
// You now cannot access the test variable
// defined outside this function. This is called
// shadowing.
let test = "InternalTest"
}
With classes it is the same, although you can also access the property of a class, even if "shadowed" by explicitly referring to it with self
class TestClass {
var test = "Test"
func testing() {
let test = "InternalTest"
self.test = test
}
}
Hope that is not too confusing :)