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 trial

iOS Swift Functions and Optionals Functions Function Return Types

Marius Pratz
PLUS
Marius Pratz
Courses Plus Student 2,705 Points

Redeclaration of a Constant inside a function

Each time the function calcuateArea is called, it redeclares the constant area. This does not lead to an invalid redeclaration error as I would have expected. What is different here than when a constant is redeclared inside the main program ?

println("Swift Functions")

func calculateArea(height: Int, width: Int) -> Int { let area = height * width println("The area of the room is (area)") }

1 Answer

Stone Preston
Stone Preston
42,016 Points

variables and constants declared inside a function are "local" and scoped to that function. they come into existence when the function is called and cease to exist once it finishes executing. nothing outside of the function even knows about things that happen inside the function.

the function does not care or know about anything it did in previous times it was called. each time its called its a new day for everything that happens inside it.

the area constant is not being redeclared each time, its just being declared since really its like the area constant never existed before.

On the other hand, if you declare a constant outside a function it has a global scope so something like this would generate a redeclaration error:

// not inside a function, so it has global scope, not local
let area = 15
//error: redeclaration of a constant 
let area = 16

because variables and constants declared inside a function are local and scoped to that function, you could declare a constant outside a function, and then declare another with the same name and it would be valid, since the constant inside the function is local to that function, and thus a completely different entity:

let area = 15

func doSomething() {

// perfectly fine
// this area constant is different than the area constant above. this is a local constant
let area = 16
}
Marius Pratz
Marius Pratz
Courses Plus Student 2,705 Points

Awesome, thanks for the detailed,excellent answer and for clearing that up !