// Integerslet a: Int = 42 // Platform-sized (64-bit on modern)let b: Int8 = 127let c: Int16 = 32_767let d: Int64 = 9_223_372_036_854_775_807let e: UInt = 42 // Unsigned// Floating pointlet f: Float = 3.14 // 32-bitlet g: Double = 3.141592653589793 // 64-bit (default)let h: CGFloat = 10.0 // Used in UI layout// Underscores for readabilitylet million = 1_000_000
Strings
// String basicslet s = "hello"var mutable = "hello"mutable += ", world!"// String interpolation (like template literals)let name = "Alice"let greeting = "Hello, \(name)!"let math = "2 + 2 = \(2 + 2)"// Multi-line strings (like template literals)let text = """ This is a multi-line string """// Common operationslet upper = s.uppercased()let contains = s.contains("ell")let count = s.countlet isEmpty = s.isEmpty
Functions
TypeScript
function greet(name: string): string { return `Hello, ${name}!`}const add = (a: number, b: number): number => a + bfunction log(message: string, level: string = "INFO"): void { console.log(`[${level}] ${message}`)}
Swift
// Basic functionfunc greet(name: String) -> String { "Hello, \(name)!" // Implicit return for single expressions}// Argument labels (external + internal names)func greet(person name: String) -> String { "Hello, \(name)!"}greet(person: "Alice")// Omit external label with _func add(_ a: Int, _ b: Int) -> Int { a + b}add(1, 2) // No labels needed// Default parametersfunc log(_ message: String, level: String = "INFO") { print("[\(level)] \(message)")}log("Hello")log("Hello", level: "DEBUG")// Closures (like arrow functions)let add = { (a: Int, b: Int) -> Int in a + b}// Shorthand closure syntaxlet doubled = [1, 2, 3].map { $0 * 2 }let sum = [1, 2, 3].reduce(0) { $0 + $1 }// Or even shorter with operatorlet sum = [1, 2, 3].reduce(0, +)// Trailing closure syntaxlet evens = [1, 2, 3, 4].filter { $0 % 2 == 0 }
Optionals (null safety)
This is a key concept in Swift. There’s no null or undefined - instead, Swift uses Optionals.
TypeScript
function find(id: number): User | undefined { return users.find(u => u.id === id)}const user = find(1)if (user) { console.log(user.name)}console.log(user?.name ?? "Unknown")
Swift
// Optional type (can be nil)var name: String? = "Alice"var missing: String? = nil// Unwrapping optionals// 1. if let (like if (value) in TS)if let name = name { print("Name: \(name)")}// 2. guard let (early return)func greet(_ name: String?) -> String { guard let name = name else { return "Hello, stranger!" } return "Hello, \(name)!"}// 3. Optional chaining (like ?.)let count = name?.count // Int?// 4. Nil coalescing (like ??)let displayName = name ?? "Unknown"// 5. Force unwrap (like ! in TS - avoid!)let forced = name! // Crashes if nil!// 6. map / flatMap on optionalslet uppercased = name.map { $0.uppercased() } // String?// Optional binding with multiple valuesif let name = name, let age = age, age > 18 { print("\(name) is an adult")}
// Struct (value type - preferred in SwiftUI)struct User { let id: Int var name: String var email: String? // Computed property var displayName: String { email.map { "\(name) (\($0))" } ?? name } // Method func greet() -> String { "Hello, \(name)!" } // Mutating method (modifies struct) mutating func updateName(_ newName: String) { name = newName }}// Memberwise initializer (auto-generated)let user = User(id: 1, name: "Alice", email: nil)// Custom initializerstruct User { let id: Int var name: String init(id: Int, name: String) { self.id = id self.name = name }}// Class (reference type - use for shared state)class UserService { private var users: [User] = [] func addUser(_ user: User) { users.append(user) }}
Struct vs class
// Struct = value type (copied on assignment)var a = User(id: 1, name: "Alice", email: nil)var b = ab.name = "Bob"print(a.name) // "Alice" (unchanged)// Class = reference type (shared on assignment)let service1 = UserService()let service2 = service1service2.addUser(user)// service1 and service2 point to same instance
Enums
TypeScript
type Status = "pending" | "active" | "inactive"type Result<T, E> = | { ok: true; value: T } | { ok: false; error: E }
Swift
// Simple enumenum Status { case pending case active case inactive}let status = Status.active// Or shorthand when type is knownlet status: Status = .active// Enum with associated values (like discriminated unions)enum Message { case quit case move(x: Int, y: Int) case write(String) case changeColor(r: UInt8, g: UInt8, b: UInt8)}let msg = Message.move(x: 10, y: 20)let msg = Message.write("hello")// Pattern matching (like switch but exhaustive)switch msg {case .quit: print("Quit")case .move(let x, let y): print("Move to \(x), \(y)")case .write(let text): print("Text: \(text)")case .changeColor(let r, let g, let b): print("Color: \(r), \(g), \(b)")}// Enum with raw valuesenum Direction: String { case north = "N" case south = "S" case east = "E" case west = "W"}let dir = Direction.northprint(dir.rawValue) // "N"let dir = Direction(rawValue: "N") // Optional<Direction>// Enum with methodsenum Temperature { case celsius(Double) case fahrenheit(Double) var asCelsius: Double { switch self { case .celsius(let c): return c case .fahrenheit(let f): return (f - 32) * 5 / 9 } }}
Result type (built-in)
// Result<Success, Failure> - like TS Result typeenum NetworkError: Error { case notFound case serverError(Int)}func fetchUser(id: Int) -> Result<User, NetworkError> { if id <= 0 { return .failure(.notFound) } return .success(User(id: id, name: "Alice", email: nil))}// Handling Resultswitch fetchUser(id: 1) {case .success(let user): print("Got user: \(user.name)")case .failure(let error): print("Error: \(error)")}// Or with get()let user = try? fetchUser(id: 1).get() // Optional<User>
// Codable - JSON encoding/decoding (like serde)struct User: Codable { let id: Int let name: String}// Equatable - equality comparisonstruct Point: Equatable { let x: Double let y: Double}// Hashable - can be used in Sets and Dictionary keysstruct Id: Hashable { let value: Int}// Identifiable - common in SwiftUI listsstruct Item: Identifiable { let id: UUID let title: String}// CustomStringConvertible - toString()struct User: CustomStringConvertible { let name: String var description: String { "User(\(name))" }}
Collections
TypeScript
const arr: number[] = [1, 2, 3]arr.push(4)const doubled = arr.map(n => n * 2)const evens = arr.filter(n => n % 2 === 0)const sum = arr.reduce((a, b) => a + b, 0)
Swift
// Arrayvar arr = [1, 2, 3]arr.append(4)// Functional operations (eager, not lazy by default)let doubled = arr.map { $0 * 2 }let evens = arr.filter { $0 % 2 == 0 }let sum = arr.reduce(0, +)// Or with trailing closurelet sum = arr.reduce(0) { $0 + $1 }// Iterationfor n in arr { print(n)}for (i, n) in arr.enumerated() { print("\(i): \(n)")}// Common methodsarr.countarr.isEmptyarr.contains(2)arr.first // Optionalarr.last // Optionalarr.firstIndex(of: 2)arr.sorted()arr.reversed()arr.compactMap { Int($0) } // Filter nil valuesarr.flatMap { [$0, $0] }arr.prefix(2) // First 2arr.suffix(2) // Last 2arr.dropFirst()arr.dropLast()// Lazy evaluation (like Rust iterators)let result = arr.lazy .filter { $0 % 2 == 0 } .map { $0 * 2 } .prefix(5)
struct CounterView: View { @State private var count = 0 var body: some View { VStack(spacing: 20) { Text("Count: \(count)") Button("Increment") { count += 1 } } .padding() }}
SwiftUI state management
React state vs SwiftUI property wrappers
React
SwiftUI
Use case
useState
@State
Local component state
useRef
Regular property
Non-reactive value
props
Regular let/var
Passed from parent
useState + callback
@Binding
Two-way parent-child binding
useContext
@Environment
App-wide values
useContext + reducer
@Observable
Shared mutable state
useMemo
Computed property
Derived values
@State (local state)
struct ToggleView: View { @State private var isOn = false var body: some View { Toggle("Switch", isOn: $isOn) // $ creates a Binding Text(isOn ? "ON" : "OFF") }}
@Binding (two-way props)
// Like passing setState down as a propstruct ParentView: View { @State private var name = "" var body: some View { ChildView(name: $name) // Pass binding Text("Hello, \(name)") }}struct ChildView: View { @Binding var name: String var body: some View { TextField("Enter name", text: $name) }}
@Observable (shared state)
import Observation// Like a context + reducer@Observableclass AppState { var user: User? var isLoading = false var items: [Item] = [] func loadItems() async { isLoading = true items = await api.fetchItems() isLoading = false }}struct ContentView: View { var state = AppState() var body: some View { if state.isLoading { ProgressView() } else { List(state.items) { item in Text(item.title) } } }}
@Environment (dependency injection)
// Like React Contextstruct ContentView: View { @Environment(\.colorScheme) var colorScheme @Environment(\.dismiss) var dismiss var body: some View { Text("Mode: \(colorScheme == .dark ? "Dark" : "Light")") Button("Close") { dismiss() } }}
SwiftUI views and layout
React JSX vs SwiftUI
// VStack = flexbox columnVStack(alignment: .leading, spacing: 10) { Text("Title") .font(.title) Text("Subtitle") .foregroundStyle(.secondary)}// HStack = flexbox rowHStack(spacing: 12) { Image(systemName: "star.fill") Text("Favorites") Spacer() // Like flex-grow Text("42")}// ZStack = position absolute / z-indexZStack { Color.blue // Background Text("Overlay") .foregroundStyle(.white)}// ScrollViewScrollView { VStack { ForEach(items) { item in Text(item.title) } }}// List (like a styled ul with built-in features)List(items) { item in HStack { Text(item.title) Spacer() Text(item.detail) .foregroundStyle(.secondary) }}