Swift-Cheatsheet

👋 Hello World

import Foundation

print("Hello, World!")

💡 Tip: In Swift, print() automatically adds a newline — no semicolon needed!

📦 Variables & Constants

var name = "Maxon"   // variable (mutable)
let pi = 3.14159     // constant (immutable)
var age: Int = 25    // explicit type

💡 Tip: Use let for constants — Swift prefers immutability.

🔢 Data Types

let isSwiftFun: Bool = true
let score: Int = 100
let temperature: Double = 36.6
let initial: Character = "S"
let message: String = "Swift Rocks!"

💡 Tip: Swift is strongly typed, but supports type inference.

🔀 Control Flow

for i in 1...5 {
    if i % 2 == 0 {
        print("\(i) is Even")
    } else {
        print("\(i) is Odd")
    }
}

var grade = "B"
switch grade {
case "A": print("Excellent")
case "B": print("Good")
default: print("Keep trying!")
}

💡 Tip: switch in Swift must be exhaustive — cover all cases.

🧮 Functions

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

print(greet(name: "Maxon"))

💡 Tip: Swift functions use named parameters by default.

🔁 Multiple Return Values (Tuples)

func getStats() -> (min: Int, max: Int) {
    return (1, 100)
}

let result = getStats()
print(result.min, result.max)

💡 Tip: Tuples are a great way to return multiple values.

📚 Classes & Objects

class Car {
    var brand: String
    var speed: Int

    init(brand: String, speed: Int) {
        self.brand = brand
        self.speed = speed
    }

    func drive() {
        print("\(brand) drives at \(speed) km/h")
    }
}

let c = Car(brand: "Tesla", speed: 120)
c.drive()

💡 Tip: init() is the initializer (like constructors in other languages).

🧩 Structs

struct Rectangle {
    var width: Double
    var height: Double

    func area() -> Double {
        return width * height
    }
}

let rect = Rectangle(width: 5, height: 3)
print(rect.area())

💡 Tip: Structs are value types — copied by value, unlike classes.

⚙️ Protocols

protocol Shape {
    func area() -> Double
}

struct Circle: Shape {
    var radius: Double
    func area() -> Double {
        return 3.14 * radius * radius
    }
}

💡 Tip: Protocols define behavior — similar to interfaces.

💥 Optionals

var name: String? = "Maxon"
print(name!) // force unwrap
if let safeName = name {
    print("Hello, \(safeName)")
}

💡 Tip: Use if let or guard let to safely unwrap optionals.

🧰 Error Handling

enum MyError: Error {
    case invalidInput
}

func divide(a: Int, b: Int) throws -> Int {
    if b == 0 {
        throw MyError.invalidInput
    }
    return a / b
}

do {
    try divide(a: 10, b: 0)
} catch {
    print("Error occurred: \(error)")
}

💡 Tip: Use do-catch for exceptions — Swift errors are typed.

⚡ Closures

let square = { (x: Int) -> Int in
    return x * x
}

print(square(5))

💡 Tip: Closures are similar to lambdas or anonymous functions.

🧠 Enumerations

enum Direction {
    case north, south, east, west
}

let dir = Direction.north
switch dir {
case .north: print("Going up")
default: print("Other direction")
}

💡 Tip: Swift enums are powerful — can have raw or associated values.

🌐 Collections

var fruits = ["Apple", "Banana", "Cherry"]
fruits.append("Mango")

var scores: [String: Int] = ["Alice": 90, "Bob": 85]
scores["Charlie"] = 95

💡 Tip: Arrays, Dictionaries, and Sets are all value types in Swift.

🧭 SwiftUI Basics

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, SwiftUI!")
                .font(.largeTitle)
                .foregroundColor(.blue)
            Button("Tap Me") {
                print("Tapped!")
            }
        }
    }
}

💡 Tip: SwiftUI uses a declarative syntax — define your UI as data.

🧩 Extensions

extension String {
    func reversedString() -> String {
        return String(self.reversed())
    }
}

print("Swift".reversedString())

💡 Tip: Use extensions to add functionality to existing types.

🧱 Generics

func swapValues<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}

var x = 5, y = 10
swapValues(&x, &y)

💡 Tip: Generics make your code reusable and type-safe.

Post a Comment