Chapter 4: Understanding Swift Basics: Variables, Constants, and Data Types
This post is part of a series about programming with Swift to build iOS apps. Be sure to check out the other posts in the series for a complete journey into mastering iOS development.
Now that you’ve built and run your first app, it’s time to take a closer look at the programming language that powers iOS development: Swift. Swift is fast, safe, and easy to learn, making it an excellent choice for building apps.
In this post, we’ll cover the fundamentals of Swift: variables, constants, and data types. These are the building blocks of your app logic, so mastering them is essential for moving forward.
What Are Variables and Constants?
In programming, a variable is a container that holds a value. Think of it as a labeled box where you can store and retrieve information. The value of a variable can change during the program’s execution.
A constant is similar to a variable, but its value cannot be changed once it’s assigned. Constants are useful for values that don’t change, like the name of your app or the number of days in a week.
Declaring Variables and Constants in Swift
Here’s how you declare variables and constants in Swift:
Variables: Use the
varkeyword.Constants: Use the
letkeyword.
// Declaring a variable
var message = "Hello, world!"
print(message) // Output: Hello, world!
// Changing the value of a variable
message = "Welcome to Swift"
print(message) // Output: Welcome to Swift
// Declaring a constant
let appName = "MyFirstApp"
print(appName) // Output: MyFirstApp
// Trying to change a constant (this will cause an error)
// appName = "NewName" // Error: Cannot assign to 'appName' because it is a 'let' constantUnderstanding Data Types
Every variable or constant has a data type, which defines the kind of value it can hold. Swift is a type-safe language, meaning it ensures you’re working with the right data types.
Here are some common data types in Swift:
Strings: Text, enclosed in double quotes (
" ")
Example:
let greeting: String = "Hello, Swift!"Integers: Whole numbers (
Int)
Example:
var score: Int = 100Floating-Point Numbers: Numbers with decimals (
DoubleorFloat)
Example:
let pi: Double = 3.14159 let temperature: Float = 36.6Booleans: True or false values (
Bool)
Example:
var isUserLoggedIn: Bool = trueArrays: Ordered collections of values
Example:
var fruits: [String] = ["Apple", "Banana", "Cherry"]Dictionaries: Key-value pairs
Example:
var user: [String: String] = ["name": "John", "email": "john@example.com"]Type Inference
Swift is smart enough to infer the type of a variable or constant based on the value you assign to it. For example:
var age = 25 // Swift infers that 'age' is an Int
let title = "Welcome" // Swift infers that 'title' is a StringHowever, you can also explicitly specify the type if you want:
var age: Int = 25
let title: String = "Welcome"Swift in Action
Let’s put these concepts into practice. Along the way, let’s learn how to add a new file to our project.
Step 1: Open Your Xcode Project
Before adding a new file, ensure your Xcode project is already open. You should see the project navigator on the left-hand side of your Xcode window, showing a list of folders and files in your project.
Step 2: Open the Project Navigator
If the project navigator isn’t visible, you can enable it by:
Clicking the folder icon in the top-left corner of the Xcode window.
Alternatively, press
Command + 1on your keyboard to bring up the project navigator.
Step 3: Select the Location for the New File
In the project navigator, click on the folder where you want to add your new Swift file.
If you’re unsure, you can select the project’s main folder (usually the topmost item in the navigator).
This step ensures your new file is added to the right location within your project structure.
Step 4: Add a New File
Right-click on the folder you selected in the project navigator.
From the context menu, choose New File….
Alternatively, you can go to the File menu in the top bar and select New > File….
Another option is to use the keyboard shortcut
Command + N.
Step 5: Choose a Template for Your File
A new window will pop up asking you to select a template.
Under the iOS or macOS section (depending on your project), choose Swift File and click Next.
The Swift File template creates an empty
.swiftfile where you can add your Swift code.
Step 6: Name Your File
In the next step, you’ll be asked to name your file. Enter a name that reflects the purpose of the file.
Chapter4View.swift, for example.Avoid spaces or special characters in the file name.
Click Create when you’re done.
Step 7: Verify the New File
The new Swift file will appear in the project navigator in the folder you selected earlier.
Click on the file to open it in the main editor area.
Step 8: Add the following code in Chapter4View.swift:
import SwiftUI
struct Chapter4View: View {
let userName = "Mihai" // Constant (cannot change)
let appName = "HelloWorldApp" // Constant (cannot change)
@State var greeting: String // Variable (can change)
init() {
self.greeting = "Welcome to \(appName), \(userName)!" // 1
}
var body: some View {
VStack {
Text(greeting)
.font(.title)
.padding()
// Simulate changing the value of 'greeting'
Button("Change Greeting") {
greeting = "Let’s start coding in Swift!"
}
.padding()
}
}
}Step 9: Add the following code in ContentView.swift:
import SwiftUI
struct ContentView: View {
var body: some View {
Chapter4View() //
}
}
#Preview {
ContentView()
}Explanation of the Code
For now, don’t take into account the usage of the @State (property wrapper).
String Interpolation: The code uses
\( )to embed variables directly into a string, making it dynamic.
self.greeting = "Welcome to \(appName), \(userName)!"This replaces \(appName) and \(userName) with their respective values.
Updating Variables: You see how
greetingchanges midway through the app, demonstrating variable mutability.Using Constants: Both
userNameandappNameare declared as constants (let) because they don’t change.
Challenge: Try It Yourself
Declare a constant for your favorite programming language and display it on the screen.
Create a variable for today’s weather and update it midway through the app.
Example:
let favoriteLanguage = "Swift"
var weather = "Sunny"
weather = "Cloudy"What’s Next?
You now have a solid understanding of variables, constants, and data types in Swift. These concepts are fundamental to every app you’ll build, so practice them as much as you can.
In the next post, we’ll explore control flow—how to make decisions in your code using conditionals and loops. This is where you’ll start to see how logic brings apps to life.
Let’s keep the momentum going!

