[Swift Apple ] 4. Constants Never Change!

Last time, we learned about variables. A variable is like a labeled box where we can change what’s inside anytime we want. Now, let’s learn something a little different — a “label that never changes its value”, called a constant in Swift!







🔁 What’s the Difference Between Variables and Constants?


In Swift, there are two main ways to store information:

Name

Can You Change the Value?

Keyword Used

Variable

✅ Yes, you can change it

var

Constant

❌ No, it can’t be changed

let

So, if you want a value that can change, use var.

But if the value should never change, use let.



🎂 Practice: My Birthday Never Changes!


Does your birthday change? Of course not!

It happens once a year, but the date always stays the same.


That’s why we should save it using a constant, not a variable.

let myBirthday = "2014-05-10"
print("My birthday is \(myBirthday).")

Output:

My birthday is 2014-05-10.

Now try to change your birthday like this:

myBirthday = "2020-01-01"

Uh-oh! ❗️ Swift knows that you’re trying to change the value of a constant,

so it will show you an error message — usually in red!








Because constants should never change, Swift will stop you from changing it.



🔐 When Should You Use Constants?


Use constants when:

You want to store information that never changes

e.g. your birthday, a fixed file name, a set value

You want to protect a value from being changed by mistake

e.g. app settings, personal information


Think of constants as a safety shield that keeps your values safe from being changed accidentally.


✨ Wrapping Up


Today, we learned about constants (let)

they are just like variables, but the value never changes!


Let’s remember:

If the value can change, use varvariable

If the value should never change, use letconstant


That’s how we decide which one to use when writing Swift code!

댓글 쓰기