Types
Basic Types
Integers
Imagine you're counting apples. If you have 3 apples, we call that a number. Now, if you want to add more apples, you can use integers to help!
An integer is just a fancy word for a number. It can be positive (like 5 or 10) or negative (like -2 or -7), and it doesn't have any parts like a decimal (2.5 or -6.50).
Let’s say you have 3 apples. In Swift, we write it like this:
var apples: Int = 3
Now, if your friend gives you 3 more apples, you can add them together like this:
var totalApples: Int = apples + 3
But what if you lose 1 apple? You can take away 1 like this:
let newTotal: Int = totalApples - 1
What if you owe apples?
Imagine you accidentally fall on top of your friend's 10 apples, and you feel bad about it. So, you offer to give your friend 5 apples to make up for it. But you still owe, your friend 5 apples because you didn’t have enough to replace all the apples you broke!
In Swift, you can show that you owe your friend 5 apples by writing it like this:
let applesOwed: Int = -5
So, with Swift, you can use numbers to add, take away, and even keep track of things you owe, all with integers!
Numeric literals can be padded with zeros and contain underscores for readability.
let millionApples: Int = 1_000_000
Signed Integers
Signed integers can hold positive, negative, and zero values.
Integer Type | Size (bits) | Minimum Value | Maximum Value |
---|---|---|---|
Int8 | 8 | -128 | 127 |
Int16 | 16 | -32,768 | 32,767 |
Int32 | 32 | -2,147,483,648 | 2,147,483,647 |
Int64 | 64 | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
Int | Platform-dependent x32 x64 | -2,147,483,648 -9,223,372,036,854,775,808 | 2,147,483,647 9,223,372,036,854,775,807 |
Signed integers has min and max properties that allow you to access the smallest and largest values and here is how you can access it:
print("--- Signed Integers ---")
print("Int8: \(Int8.min) to \(Int8.max)")
print("Int16: \(Int16.min) to \(Int16.max)")
print("Int32: \(Int32.min) to \(Int32.max)")
print("Int64: \(Int64.min) to \(Int64.max)")
print("Int: \(Int.min) to \(Int.max)")
Unsigned Integers
Unsigned integers can only hold positive values and zero.
Integer Type | Size (bits) | Minimum Value | Maximum Value |
---|---|---|---|
UInt8 | 8 | 0 | 255 |
UInt16 | 16 | 0 | 65,535 |
UInt32 | 32 | 0 | 4,294,967,295 |
UInt64 | 64 | 0 | 18,446,744,073,709,551,615 |
UInt | Platform-dependent x32 x64 | 0 0 | 4,294,967,295 18,446,744,073,709,551,615 |
Unsigned integers has min and max properties that allow you to access the smallest and largest values and here is how you can access it:
print("--- Unsigned Integers ---")
print("UInt8: \(UInt8.min) to \(UInt8.max)")
print("UInt16: \(UInt16.min) to \(UInt16.max)")
print("UInt32: \(UInt32.min) to \(UInt32.max)")
print("UInt64: \(UInt64.min) to \(UInt64.max)")
print("UInt: \(UInt.min) to \(UInt.max)")
Note
- Unless you need a specific integer size, it is advised to use
Int
for integer values in your code. - Reserve
UInt
for cases where you specifically need an unsigned integer type that matches the word size of the platform on which the program is running. - It is also advised to use
Int
, even if you know the numbers you want to keep are always positive.
Floating-Point Numbers
Floating-point numbers are numbers that can have a whole part (like 1 apple) and a fractional part (like half an apple, which is written as 0.5).
For example: 3.5 means 3 apples and half of another apple and 0.25 means a quarter of an apple. In Swift, we write it like this:
let applesOwed: Double = 3.5
let applesReminaing: Float = 0.25
Floating-point literals can be padded with zeros and contain underscores for readability.
let applesOwed: Float = 3.5
let applesReminaing: Double = 000.250
Types of Floating-Point Numbers
In Swift, floating-point numbers are implemented using two primary data types:
-
Double: A 64-bit floating-point number.
-
Float: A 32-bit floating-point number.
Differences Between Double and Float
-
Precision: Double offers precision of at least 15 decimal digits, which makes it suitable for most calculations that require high precision, such as financial computations or scientific simulations. Float has a precision of about 6 decimal digits, which is sufficient for many simple applications but may introduce rounding errors in more complex computations.
-
Range: Both Double and Float can represent very large or very small values, but Double can represent a wider range of values than Float. This is due to its larger bit size (64 bits for Double vs. 32 bits for Float), which allows it to store more significant digits and larger exponents.
-
Performance: While Float uses less memory and might be more efficient in terms of processing on certain hardware (especially for performance-critical applications), Double is generally preferred due to its higher precision and compatibility with most modern hardware and software systems.
Booleans
Booleans represent logical values that can either be true
or false
. They are useful when you need to make decisions or control the flow of your program.
Let’s learn about Booleans with a few examples from real life. Here are some common situations where Booleans come in handy!
Checking If an Apple is Red
Imagine you're sorting apples, and you want to check if an apple is red. You could use a Boolean to represent this:
let isAppleRed: Bool = true
Here, isAppleRed is a Boolean constant set to true because the apple is indeed red. You can use this Boolean value to control your program's behavior:
if isAppleRed {
print("This apple is red!")
} else {
print("This apple is not red.")
}
This apple is red!
Checking if a Student Passed a Test
Imagine a student named Matha who just took a test. We want to check if she passed the test based on her score:
let didMathaPass: Bool = true // Matha passed the test
We can now use this Boolean to print a message about her performance:
if didMathaPass {
print("Congratulations, Matha! You passed the test.")
} else {
print("Sorry, Matha. You didn't pass the test.")
}
Congratulations, Matha! You passed the test.
Checking if a User is Logged In
Let’s say you’re building an app where users can log in. You might need a Boolean to check if a user is logged in:
let isUserLoggedIn: Bool = false // The user is not logged in
Based on this, you can control the flow of the app, for instance, showing the login screen if the user isn't logged in:
if isUserLoggedIn {
print("Welcome back!")
} else {
print("Please log in to continue.")
}
Output will be: Please log in to continue.
Tuples
In Swift, tuples are a powerful way to group multiple related values together into a single, neat structure. The best part? The values inside a tuple can be of any type and don’t need to be the same. You can mix and match numbers, strings, and even more complex objects.
Let’s learn about Tuples with a few examples from real life. Here are some common situations where Tuples come in handy!
School ID Card
Let’s imagine you're in school, and you have a Student ID Card. Your Student ID Card has a few important pieces of information:
- Your name
- Your age
- Your student ID number
- Your grade
- Your blood group
Instead of writing each of these pieces of information down separately, we can use a tuple in Swift to keep everything together in one place, just like how your Student ID Card holds all your details!
Let’s say your name is Bharat, you're 16 years old, your student ID number is 12345, you are in Grade 10, and your Blood Group is B+. You can store all of this information in a tuple like this:
let student = (name: "Bharat", age: 16, studentID: 12345, grade: "10", bloodGroup: "B+")
Now, if you want to know any piece of information about Bharat, you can access it using the tuple's parts:
let studentName = student.name // "Bharat"
let studentAge = student.age // 16
let studentID = student.studentID // 12345
let studentGrade = student.grade // "10"
let studentBloodGroup = student.bloodGroup // "B+"
You can access all values at once as follows:
let (studentName, studentAge, studentID, studentGrade, studentBloodGroup) = student
You can also skip few values as follows:
let (studentName, _, studentID, studentGrade, _) = student
Aadhaar Card
Let’s imagine you're in India, and you have a Aadhaar Card. Your Aadhaar Card has a 7 important pieces of information:
- Name
- Birth Date
- Gender
- Aadhaar Number
- Virtual Aadhaar Number
- Issue Date
- Address
You can store all of this information in a tuple like this:
let aadhaarCard = (
name: "Bharata Bhoomi",
birthDate: "01/01/1990",
gender: "Male",
aadhaarNumber: 1234_5678_9012,
virtualAadhaarNumber: 1234_5678_9012_3456,
issueDate: "01/01/2020",
address: "123, Kartvya Street, Delhi, India"
)
This tuple is of type: (String, String, String, Int, Int, String, String)
You can access tuple values in multiple ways as we learnt in previous example. Here is how to access the tuple elements directly by their names:
print("Name: \(aadhaarCard.name)")
Note
While tuples are great for grouping related values, they aren’t always the best choice when you have more complex data or need to model more detailed structures. If you find yourself needing to group many values or creating a complex structure, it’s better to use classes or structures instead of tuples.