Swift First Program
Welcome to the exciting world of Swift programming! In this lesson, you'll create your very first Swift program. We'll start with the traditional "Hello, World!" example that programmers have been using for decades as their first program in a new language.
Introduction to Swift Programs
Swift is a powerful and intuitive programming language developed by Apple for building iOS, macOS, watchOS, and tvOS applications. Before diving into complex applications, it's important to understand the basic structure of a Swift program.
A Swift program can be as simple as a single line of code or as complex as thousands of lines organized into multiple files. Either way, you need to understand the fundamentals before moving to more advanced concepts.
Setting Up Your Environment
Before writing your first Swift program, you need a development environment. You have several options:
- Xcode: The official integrated development environment (IDE) for macOS
- Swift Playgrounds: A beginner-friendly app for iPad and Mac
- Online Swift REPL: Web-based environments like Replit
- Swift on Linux: For those using Linux operating systems
For this tutorial, we'll assume you're using Xcode or an online Swift environment.
Your First Swift Program: Hello, World!
Let's write our first Swift program to display "Hello, World!" on the screen:
print("Hello, World!")
When you run this program, you'll see:
Hello, World!
That's it! You've just written and executed your first Swift program.
Understanding the Code
Let's break down what happened:
print
: This is a built-in Swift function that outputs text to the console.("Hello, World!")
: These are the arguments passed to the print function. In this case, we're passing the text string "Hello, World!".- The quotation marks
"..."
indicate that we're using a string literal. - The line ends with a
;
(semicolon), which is optional in Swift but commonly used in many other programming languages.
Adding Comments to Your Code
Comments are notes in your code that the compiler ignores. They help you and others understand what your code does:
// This is a single-line comment
/*
This is a multi-line comment
It can span several lines
Very useful for longer explanations
*/
print("Hello, World!") // This prints a greeting message
Variables and Constants in Your First Program
Let's enhance our program by using variables and constants:
// Using a variable (can change)
var greeting = "Hello"
greeting = "Hi" // We can change it later
// Using a constant (cannot change)
let name = "Swift Programmer"
// Combining values
print("\(greeting), \(name)!")
Output:
Hi, Swift Programmer!
Notice how we used:
var
for variables whose values might changelet
for constants whose values won't change- String interpolation with
\(variableName)
to embed variables in strings
Adding User Interaction
Let's create a slightly more interactive example:
import Foundation
print("What's your name?")
let name = readLine() ?? "Anonymous" // Read input with a default value
print("Hello, \(name)! Welcome to Swift programming.")
If you run this program and enter "Alex", the output will be:
What's your name?
Alex
Hello, Alex! Welcome to Swift programming.
A Practical Example: Temperature Converter
Let's create something more practical - a simple temperature converter:
import Foundation
// Function to convert Celsius to Fahrenheit
func celsiusToFahrenheit(_ celsius: Double) -> Double {
return celsius * 9/5 + 32
}
// Get temperature input from user
print("Enter a temperature in Celsius:")
if let input = readLine(), let celsius = Double(input) {
let fahrenheit = celsiusToFahrenheit(celsius)
print("\(celsius)°C is equal to \(fahrenheit)°F")
} else {
print("Invalid input. Please enter a valid number.")
}
If you enter "25", the output will be:
Enter a temperature in Celsius:
25
25.0°C is equal to 77.0°F
This example introduces:
- Functions in Swift
- Optional handling with
if let
- Type conversion with
Double(input)
- More advanced string interpolation
Understanding the Swift Entry Point
Unlike some other programming languages (like Java or C), Swift doesn't require a specific main function or entry point for simple programs. The code is executed from top to bottom.
However, for more complex applications (like iOS apps), Swift uses specific entry points that we'll explore in future lessons.
Summary
Congratulations! You've written your first Swift program and learned about:
- The basic syntax of Swift
- How to print output to the console
- Adding comments to your code
- Using variables and constants
- Basic string manipulation and interpolation
- Reading user input
- Creating a simple function
- Building a practical temperature converter
These fundamentals will serve as building blocks as you continue your Swift programming journey.
Exercises to Practice
- Modify the "Hello, World!" program to greet yourself by name.
- Create a program that asks for your age and tells you how old you'll be in 10 years.
- Write a program that converts miles to kilometers (1 mile = 1.60934 kilometers).
- Create a simple calculator that can add two numbers entered by the user.
Additional Resources
- Swift Official Documentation
- Apple's Swift Programming Language Guide
- Swift Playgrounds - A fun way to learn Swift programming
Now that you've written your first Swift program, you're ready to explore more complex Swift concepts and start building amazing applications!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)