Swift Fundamentals Cheatsheet

Quick reference for Swift programming: syntax, data types, control flow, functions, OOP, protocols, and modern features.

FeatureDescriptionExampleCategory
VariablesDeclare mutable variablesvar name = "John" var age: Int = 25Basics
ConstantsDeclare immutable valueslet pi = 3.14159 let maxUsers: Int = 100Basics
String InterpolationEmbed variables in stringslet greeting = "Hello, \(name)!" print(greeting)Basics
Type InferenceAutomatic type detectionlet number = 42 // Inferred as Int let text = "Swift" // StringBasics
ArraysOrdered collectionsvar numbers = [1, 2, 3, 4, 5] numbers.append(6) let first = numbersData Types
DictionariesKey-value pairsvar person = ["name": "John", "age": "25"] person["city"] = "NYC"Data Types
SetsUnique unordered valuesvar colors: Set = ["red", "blue", "green"] colors.insert("yellow")Data Types
TuplesGroup multiple valueslet http404 = (404, "Not Found") print(http404.0) // 404Data Types
If-ElseConditional executionif age >= 18 { print("Adult") } else { print("Minor") }Control Flow
SwitchMultiple condition matchingswitch grade { case "A": print("Excellent") case "B": print("Good") default: print("Other") }Control Flow
For LoopIterate over sequencesfor i in 1...5 { print(i) } for item in array { print(item) }Control Flow
While LoopCondition-based iterationvar count = 0 while count < 5 { count += 1 }Control Flow
GuardEarly exit validationguard let name = optionalName else { return } print(name)Control Flow
Basic FunctionDefine reusable code blocksfunc greet(name: String) -> String { return "Hello, \(name)!" }Functions
Multiple ParametersFunctions with multiple inputsfunc add(_ a: Int, _ b: Int) -> Int { return a + b }Functions
Default ParametersOptional parameter valuesfunc greet(name: String = "Guest") { print("Hello, \(name)") }Functions
Variadic ParametersAccept variable number of argumentsfunc sum(_ numbers: Int...) -> Int { return numbers.reduce(0, +) }Functions
ClosuresAnonymous functionslet multiply = { (a: Int, b: Int) -> Int in return a * b }Functions
ClassDefine reference typesclass Person { var name: String init(name: String) { self.name = name } }OOP
StructDefine value typesstruct Point { var x: Int var y: Int }OOP
PropertiesStored and computed propertiesvar fullName: String { return "\(firstName) \(lastName)" }OOP
MethodsFunctions within typesfunc speak() { print("Hello from \(name)") }OOP
InheritanceExtend existing classesclass Student: Person { var grade: String init(name: String, grade: String) { self.grade = grade super.init(name: name) } }OOP
Protocol DefinitionDefine requirementsprotocol Identifiable { var id: String { get } func identify() }Protocols
Protocol ConformanceImplement protocol requirementsclass User: Identifiable { var id: String func identify() { print(id) } }Protocols
Protocol ExtensionAdd default implementationsextension Identifiable { func describe() { print("ID: \(id)") } }Protocols
Optional DeclarationValues that may be nilvar middleName: String? = nil var age: Int? = 25Optionals
Optional BindingSafely unwrap optionalsif let name = optionalName { print(name) }Optionals
Force UnwrappingUnwrap with ! (use carefully)let forcedName = optionalName! print(forcedName)Optionals
Nil CoalescingProvide default valueslet name = optionalName ?? "Guest" print(name)Optionals
Optional ChainingSafely access nested optionalslet length = person?.address?.street?.countOptionals
EnumsDefine enumeration typesenum Direction { case north, south, east, west }Advanced
GenericsWrite flexible, reusable codefunc swap<T>(_ a: inout T, _ b: inout T) { let temp = a a = b b = temp }Advanced
Error HandlingHandle errors with try-catchdo { try riskyOperation() } catch { print("Error: \(error)") }Advanced
ExtensionsAdd functionality to existing typesextension String { func capitalized() -> String { return self.uppercased() } }Advanced
Map/Filter/ReduceFunctional collection operationslet doubled = [1,2,3].map { $0 * 2 } let evens = [1,2,3].filter { $0 % 2 == 0 }Advanced