Swift Introduction

Getting Started with Swift

Welcome to the world of Swift! Swift is a powerful and intuitive programming language developed by Apple for building apps across all Apple platforms (iOS, macOS, watchOS, tvOS) and beyond. It's designed to be safe, fast, and modern, making it a joy to write and read.

Why Swift?

Your First Swift Code

Let's write a classic "Hello, World!" program. Open a Swift playground (if you're on a Mac with Xcode) or an online Swift editor to try this out.


// This is a comment in Swift
var greeting = "Hello, World!"
print(greeting)
        

When you run this code, it will print Hello, World! to the console.

Understanding the Code:

var greeting = "Hello, World!": This line declares a variable named greeting and assigns the text string "Hello, World!" to it. The var keyword is used for mutable variables, meaning their values can be changed later.

print(greeting): This function displays the value of the greeting variable to the output.

Variables and Constants

In Swift, you'll often work with data. You store data in variables and constants.


let maximumLoginAttempts = 10 // A constant, cannot be changed
var currentLoginAttempts = 0 // A variable, can be changed
currentLoginAttempts = 1
        

Data Types

Swift is a statically typed language, meaning the type of a variable or constant is checked at compile time. However, Swift can often infer the type for you.

Type Inference:

Swift is smart enough to figure out the type based on the value you provide. In the greeting example, Swift knows it's a String. In the maximumLoginAttempts example, it knows it's an Int.

Basic Operations

Swift supports standard arithmetic operations:


let apples = 5
let oranges = 3
let totalFruits = apples + oranges
print("Total fruits: \(totalFruits)") // String interpolation
        

The \(variableName) syntax is called string interpolation, allowing you to embed values of constants and variables directly within a string literal.

💡

Pro Tip: Always prefer let for constants. It makes your code safer and easier to reason about, as you know that value won't change unexpectedly.

Next Steps

This is just the beginning! In the next tutorials, we'll explore more advanced Swift concepts like collections (arrays and dictionaries), control flow (if statements, loops), functions, and object-oriented programming with classes and structs.

Keep practicing, and don't hesitate to experiment with the code!