iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Syntax

Swift syntax tour: variables, optionals, control flow, structs, classes, enums, protocols, generics, async/await.

Swift — syntax tour

EXAMPLE
// ===== Variables =====
let pi: Double = 3.14          // immutable
var count = 0                  // mutable
count += 1

// ===== Optionals =====
let maybe: String? = nil
if let value = maybe { print(value) }
let length = maybe?.count ?? 0

// Force unwrap (use sparingly):
let forced = maybe!

// ===== Strings =====
let name = "Alex"
let g = "Hello \(name)"        // interpolation
let multiline = """
multi
line
"""

// ===== Collections =====
let nums = [1, 2, 3]
var ages: [String: Int] = ["Alex": 30]
var tags: Set<String> = ["vip", "beta"]

nums.map { $0 * $0 }            // [1, 4, 9]
nums.filter { $0 > 1 }
nums.reduce(0, +)

// ===== Control flow =====
if count > 0 { /* ... */ } else { /* ... */ }
for n in 1...10 { print(n) }
while count < 5 { count += 1 }

// Switch with pattern matching:
switch (count, name) {
case (0, _):              print("none")
case (1...10, let n):     print("small with \(n)")
case let (n, _) where n > 100: print("big \(n)")
default:                  print("other")
}

// ===== Structs (value types) =====
struct Point {
    var x: Double
    var y: Double
    static let origin = Point(x: 0, y: 0)
    func distance(to other: Point) -> Double {
        ((x - other.x) ** 2 + (y - other.y) ** 2).squareRoot()
    }
}

// ===== Classes (reference types) =====
class User {
    var name: String
    init(name: String) { self.name = name }
    deinit { print("\(name) gone") }
}

// ===== Enums (with associated values) =====
enum Result<T> {
    case success(T)
    case failure(Error)
}

enum Status: String {
    case new = "new"
    case shipped = "shipped"
}

// ===== Protocols =====
protocol Describable {
    var description: String { get }
}

extension User: Describable {
    var description: String { name }
}

// ===== Generics =====
func first<T>(_ xs: [T]) -> T? { xs.first }

struct Stack<Element> {
    private var items: [Element] = []
    mutating func push(_ x: Element) { items.append(x) }
    mutating func pop() -> Element? { items.popLast() }
}

// ===== Closures =====
let square: (Int) -> Int = { $0 * $0 }
nums.sorted(by: { $0 > $1 })

// ===== async / await =====
func fetch(_ url: URL) async throws -> Data {
    let (data, _) = try await URLSession.shared.data(from: url)
    return data
}

// ===== Patterns to internalise =====
// - struct + value semantics by default
// - Use enums to model closed sets (no invalid states)
// - Protocols + generics over deep class hierarchies
// - Optionals are the language; never use NSNull-like patterns

// ===== Pitfalls =====
// - Force-unwrap (!) everywhere -> crashes
// - Reference cycles in closures -> [weak self]
// - Massive view controllers (UIKit antipattern)
// - Mixing Combine + async/await without a plan

Why it matters

Swift is one of the cleanest modern languages. Structs by default, protocols + generics for abstraction, enums with associated values for sums, async/await for I/O. Master the optionals and the pattern-matching switch and the rest of Swift starts to feel cohesive.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
let name = "Ada"
var age = 36
func greet(_ who: String) -> String { "hi, \(who)" }
print(greet(name))
Try it Yourself »

Discussion

Loading…