🔢 5. Numbers and Calculations
Hello there! 😊 Today, we’re going to learn how to use numbers in Swift coding.
We’ll talk about integers, decimals, and how to do basic math operations like addition and subtraction.
And at the end, we’ll even build a simple age calculator together! 🚀
🔢 What’s the Difference Between Int and Double?
In Swift, there are two main types of numbers:
Type |
What It Means |
Example Values |
Swift Type |
---|---|---|---|
Integer |
Whole numbers (no dots) |
3, 10, -5 |
Int |
Decimal |
Numbers with dots |
3.14, -2.5 |
Double |
Example:
var age: Int = 10
var pi: Double = 3.14
Use Int when you’re working with whole numbers,
and Double when you need decimal points (like in math or science).
➕➖✖️➗ Doing Math in Swift
Swift makes it easy to do basic math just like in school:
Operation |
Symbol |
Example Code |
Result |
---|---|---|---|
Addition |
+ |
2 + 3 |
5 |
Subtraction |
- |
10 - 4 |
6 |
Multiplication |
* |
3 * 5 |
15 |
Division |
/ |
10 / 2 |
5 |
Sample Code:
let a = 10
let b = 4
print(a + b) // 14
print(a - b) // 6
print(a * b) // 40
print(a / b) // 2
Note: If you divide two Int numbers, the result will also be an Int (no decimals).
For example: 9 / 2 will give you 4 instead of 4.5.
🧪 Practice: Build an Age Calculator
Now it’s time to write your own code!
Let’s build a simple age calculator.
let birthYear = 2014
let thisYear = 2025
let age = thisYear - birthYear
print("You are \(age) years old.")
Output:
You are 11 years old.
Try changing the birthYear and see how the result changes! 😄
💡 Bonus: Life Expectancy Calculator
Want a little challenge?
Let’s say the average life expectancy is 100 years.
You can also calculate how many years you have left!
let lifeExpectancy = 100
let remaining = lifeExpectancy - age
print("You might have \(remaining) more years to live!")
This is a fun way to mix math with real-world ideas.
✨ Wrapping Up
Today, we learned how to use numbers in Swift:
• Int = whole numbers
• Double = decimal numbers
• Math operations: +, -, *, /
• We built a simple age calculator! 🎉
In the next lesson, we’ll learn how to work with letters and sentences in Swift.
It’s called: ✉️ Letters and Words!
See you next time on our Swift coding journey! 😊🚀
댓글 쓰기