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 trialParker Rose
1,741 PointsWhy would you ever use a constant when you could use a variable instead?
Wouldn't it just be more convient?
3 Answers
Steven Deutsch
21,046 PointsHey Parker Rose,
Good question! You use a constant over a variable for values that you NEVER want to change in your code. This helps the compiler make better optimizations and naturally prevent a lot of bugs from occurring. There will be places in your code where if a specific value was able to be mutated, this could become problematic.
For example:
// Let's say we create a constant called daysInYear and assign it an Int value of 365
let daysInYear = 365
// Let's create a variable called daysInMonth
var daysInMonth = 31
By defining daysInYear as a constant, it is much SAFER to use this value in our code, as the number of days in the year should never change. (Yes, ignore the possibility of a leap year for this example). daysInMonth on the other hand, is best as a variable because the number of days in the month can change, depending on what month it is.
Good luck!
I Hou Tong
6,936 PointsThere's a difference between the two. Variables are used when you plan on changing the value at some point while constants are used when you don't want the value to be changed, ever. This is especially helpful when you're working with others and don't want their code to change the value of a variable that should not be changed.
Hüseyin EMECAN
1,207 Pointsdo whatever you want :)