Swift Keywords

Reserved words and special identifiers in Swift

🔑 What are Swift Keywords?

Swift keywords are reserved words with special meanings in the language. They control program flow, define types, manage memory, and provide language features like optionals and generics.


// Keywords in action
var name: String = "Swift"
let isAwesome: Bool = true
if isAwesome {
    print("Swift is awesome!")
}
                                    

Keyword Categories

📦

Declaration

Define variables, functions, types

var let func class
🔄

Control Flow

Manage program execution

if else for while
🎯

Access Control

Control visibility and access

public private internal open
âš¡

Special

Unique Swift features

nil self super weak

🔹 Declaration Keywords

Keywords used to declare variables, constants, and types:

// Variable and constant declaration
var mutableValue = 10        // Can be changed
let constantValue = 20       // Cannot be changed

// Function declaration
func greet(name: String) -> String {
    return "Hello, \(name)!"
}

// Class declaration
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

// Struct declaration
struct Point {
    var x: Double
    var y: Double
}

// Enum declaration
enum Direction {
    case north, south, east, west
}

🔹 Control Flow Keywords

Keywords that control program execution:

// Conditional statements
if temperature > 30 {
    print("It's hot!")
} else if temperature < 10 {
    print("It's cold!")
} else {
    print("Nice weather!")
}

// Switch statement
switch direction {
case .north:
    print("Going north")
case .south:
    print("Going south")
default:
    print("Going somewhere else")
}

// Loops
for i in 1...5 {
    print("Number: \(i)")
}

while isRunning {
    // Do something
    break  // Exit loop
}

// Guard statement
guard let name = optionalName else {
    return
}

🔹 Access Control Keywords

Control visibility and access to code:

// Public - accessible everywhere
public class PublicClass {
    public var publicProperty = "Everyone can see this"
}

// Internal - accessible within module (default)
internal class InternalClass {
    internal var internalProperty = "Module can see this"
}

// Private - accessible within same file
private class PrivateClass {
    private var privateProperty = "Only this file can see"
}

// File-private - accessible within same file
fileprivate class FilePrivateClass {
    fileprivate var filePrivateProperty = "Same file access"
}

class Example {
    private var secret = "Hidden"
    public var visible = "Everyone can see"
}

🔹 Memory Management Keywords

Keywords for managing object references:

class Parent {
    var children: [Child] = []
}

class Child {
    weak var parent: Parent?    // Weak reference (no retain cycle)
    unowned let school: School  // Unowned reference
    
    init(school: School) {
        self.school = school
    }
}

// Strong reference (default)
var strongReference = Parent()

// Weak reference
weak var weakReference = strongReference

// Unowned reference
// unowned let unownedReference = strongReference

🔹 Special Swift Keywords

Unique keywords specific to Swift:

// nil - represents absence of value
var optionalString: String? = nil

// self - refers to current instance
class Calculator {
    var result = 0
    
    func add(_ value: Int) {
        self.result += value  // self refers to this instance
    }
}

// super - refers to parent class
class Vehicle {
    func start() {
        print("Vehicle starting")
    }
}

class Car: Vehicle {
    override func start() {
        super.start()  // Call parent's start method
        print("Car engine started")
    }
}

// inout - allows function to modify parameter
func increment(_ number: inout Int) {
    number += 1
}

var count = 5
increment(&count)  // count is now 6

🔹 Type Keywords

Keywords for working with types:

// Type checking and casting
let someValue: Any = "Hello"

if someValue is String {
    print("It's a string!")
}

// Type casting
if let stringValue = someValue as? String {
    print("Casted to string: \(stringValue)")
}

// Force casting (use carefully!)
let forcedString = someValue as! String

// Type alias
typealias Coordinate = (x: Double, y: Double)
let point: Coordinate = (x: 10.0, y: 20.0)

// Associated type in protocols
protocol Container {
    associatedtype Item
    var items: [Item] { get set }
}

🧠 Test Your Knowledge

Which keyword is used to declare a constant in Swift?