No history yet

Introduction to Swift Programming

Getting Started with Swift

Swift is a modern, powerful programming language developed by Apple. It's the primary language for building apps across all Apple platforms, from your iPhone to your Mac. Swift was designed to be safe, fast, and easy to read and write. Its syntax is clean and concise, which makes it a great language for beginners.

Let's start with the classic first program: printing "Hello, world!". In Swift, it's just one line.

print("Hello, world!")

That's it. There's no need for semicolons at the end of lines, though they are allowed. The print() function simply displays the text inside the parentheses on the screen.

Variables and Data Types

In programming, you need a way to store and manage information. Swift uses variables and constants for this.

A constant is a value that cannot be changed once it's set. You declare it using the let keyword. Use constants when you know a value won't need to change, like the number of days in a week.

// This value cannot be changed later.
let daysInWeek = 7

A variable is a value that can be changed. You declare it with the var keyword. Use variables for values that might need to be updated, like a user's score in a game.

// This value can be updated.
var userScore = 100
userScore = 110 // This is valid.

Every variable and constant has a type, which tells Swift what kind of data it can store. Swift can often figure out the type on its own through a process called type inference. For example, when you write let year = 2024, Swift knows year is an integer.

Here are some of the most common data types:

TypeDescriptionExample
IntInteger, a whole number.let score = 10
DoubleA number with a fractional component.let pi = 3.14159
StringA sequence of characters.let name = "Alice"
BoolA Boolean value, either true or false.let isGameOver = false

You can also explicitly state the type if you need to, which is called type annotation. This can be useful for clarity or when you're declaring a variable without an initial value.

// Explicitly telling Swift that greeting is a String.
var greeting: String
greeting = "Hello there!"

Controlling the Flow

Programs rarely run straight from top to bottom. They need to make decisions and repeat actions. This is called control flow.

The most common way to make a decision is with an if statement. The code inside the curly braces runs only if the condition is true.

let temperature = 75

if temperature > 70 {
    print("It's a warm day.")
}

You can add an else block to run code when the condition is false, or else if to check another condition.

let score = 88

if score >= 90 {
    print("You got an A!")
} else if score >= 80 {
    print("You got a B.")
} else {
    print("Keep trying!")
}

To repeat actions, you use loops. A for-in loop is great for running a piece of code a specific number of times or for each item in a collection.

// This loop will run 5 times, for numbers 1 through 5.
for number in 1...5 {
    print("This is number \(number)")
}

A while loop runs as long as its condition remains true. Be careful with these, as you can accidentally create an infinite loop if the condition never becomes false!

var countdown = 3

while countdown > 0 {
    print(countdown)
    countdown -= 1 // Decrease countdown by 1
}

print("Liftoff!")

Building with Functions

As your programs grow, you'll want to organize your code into reusable blocks. That's what functions are for. A function is a named piece of code that performs a specific task.

You define a function using the func keyword, followed by the function's name, its parameters in parentheses, and its return type.

// A function that takes a name (String) and returns a greeting (String).
func greet(person: String) -> String {
    let greeting = "Hello, " + person + "!"
    return greeting
}

// Now, we can call the function.
let message = greet(person: "Maria")
print(message) // Prints "Hello, Maria!"

Functions can take multiple parameters and can also return no value. If a function doesn't return anything, you can omit the return type arrow -> and the type itself.

// A function that takes two integers and prints their sum.
func printSum(of a: Int, and b: Int) {
    print(a + b)
}

printSum(of: 10, and: 5) // Prints "15"

Swift also has a powerful feature called closures, which are self-contained blocks of functionality that can be passed around and used in your code. Think of them as functions without a name. You'll see them used frequently in Swift, especially for short, one-off operations.

With these building blocks, you have a solid foundation for writing your first Swift programs. Practice combining them to solve simple problems, and you'll be on your way to building complex applications.