Swift Introduction

Swift is Apple's modern programming language for iOS, macOS, watchOS, and tvOS development. It's also used for server-side development and is one of the fastest-growing languages.

Why Swift?

  • Safe — Type safety, optionals, memory management
  • Fast — Comparable to C++ performance
  • Expressive — Clean, modern syntax
  • Interoperable — Works with Objective-C
  • Cross-platform — iOS, macOS, server-side (Vapor)
  • Open source — Linux support

Hello World

SWIFT
import Foundation

// Variables and constants
let name = "Alice"         // Constant (immutable)
var age = 28               // Variable (mutable)

// String interpolation
print("Hello, \(name)! You are \(age) years old.")

// Type annotations
let pi: Double = 3.14159
let count: Int = 42
let active: Bool = true
let greeting: String = "Hello"

// Multi-line strings
let poem = """
    Roses are red,
    Violets are blue,
    Sugar is sweet,
    And so are you.
    """

Optionals

SWIFT
// Optionals — values that might be nil
var maybeName: String? = "Alice"
maybeName = nil  // OK

// Unwrapping optionals
// 1. if let
if let name = maybeName {
    print("Name: \(name)")
} else {
    print("No name")
}

// 2. guard let (early exit)
func greet(_ name: String?) {
    guard let name = name else {
        print("No name provided")
        return
    }
    print("Hello, \(name)!")  // name is non-optional here
}

// 3. Nil coalescing
let displayName = maybeName ?? "Anonymous"

// 4. Optional chaining
let upperName = maybeName?.uppercased()  // nil if maybeName is nil

// 5. Force unwrap (DANGEROUS!)
// let forced = maybeName!  // Crashes if nil!

Basic Types

SWIFT
// Numbers
let int: Int = 42
let double: Double = 3.14159
let float: Float = 3.14
let uint: UInt = 42

// Strings
let str = "Hello"
let count = str.count          // 5
let upper = str.uppercased()   // "HELLO"
let hasPrefix = str.hasPrefix("He")  // true
let greeting = str + " World"  // Concatenation

// Collections
let array = [1, 2, 3, 4, 5]
let set: Set = [1, 2, 3, 2, 1]  // {1, 2, 3}
let dict = ["Alice": 95, "Bob": 87]

// Ranges
let range = 1...10     // 1 to 10 inclusive
let halfRange = 1..<10 // 1 to 9 (exclusive)

// Type conversion
let intVal = 42
let doubleVal = Double(intVal)  // 42.0
let strVal = String(intVal)     // "42"

Control Flow

SWIFT
// if/else
let score = 85
if score >= 90 {
    print("A")
} else if score >= 80 {
    print("B")
} else {
    print("C")
}

// switch (exhaustive, no fall-through by default)
let grade = "A"
switch grade {
case "A":
    print("Excellent")
case "B":
    print("Good")
case "C":
    print("Average")
default:
    print("Other")
}

// Pattern matching in switch
let point = (3, 4)
switch point {
case (0, 0):
    print("Origin")
case (_, 0):
    print("On x-axis")
case (0, _):
    print("On y-axis")
case (-2...2, -2...2):
    print("Near origin")
case let (x, y):
    print("Point at (\(x), \(y))")
}

// for-in
for i in 1...5 {
    print(i)
}

for (index, fruit) in fruits.enumerated() {
    print("\(index): \(fruit)")
}

// while
var n = 5
while n > 0 {
    print(n)
    n -= 1
}

// where clause
for num in 1...100 where num.isMultiple(of: 3) {
    print(num)  // Only multiples of 3
}

💡 Tip: Use guard let for early returns and validation. It keeps your main logic at the top level without deep nesting.

Next: Swift Optionals