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 Basics (retired) Variables and Constants Constants

Is let always a constant?

what else could identify a constant?

1 Answer

Michael Hulet
Michael Hulet
47,913 Points

Yes, let defines a constant in Swift. Take the following code for example:

let number = 4
println(number)
number = 7

The above code would throw a compiler error, because you're trying to reassign number to 7, but it's a constant, so you can't do that. The one seeming exception is when you're working with classes. Take an instance of UILabel, for example.

let label = UILabel(frame: CGRectMake(0, 0, 100, 100))
label.text = "This is totally legal"

You can set and reset properties of classes instantiated as a constant all you want, but you can't totally reassign the constant to another instance of a class, like this:

let label = UILabel(frame: CGRectMake(0, 0, 100, 100))
//This would throw a compiler error, because you're reassigning a constant
label = UILabel(frame: CGRectMake(100, 100, 0, 0))