Swift
Updated: September 10, 2025Categories: Languages, Mobile, Apple
Printed from:
Swift Cheatsheet
Language Overview
Swift is a modern, powerful, and intuitive programming language developed by Apple. It is designed to be:
- Type-safe
- Fast and performant
- Expressive and concise
- Safe by default
- Supports both object-oriented and protocol-oriented programming paradigms
Basic Syntax
Hello World
Swift
12print("Hello, World!")
Comments
Swift
123456// Single-line comment
/*
Multi-line
comment
*/
/// Documentation comment
Data Types
Primitive Types
Swift
123456789101112131415161718// Integer Types
let int8: Int8 = 127
let int16: Int16 = 32767
let int32: Int32 = 2_147_483_647
let int64: Int64 = 9_223_372_036_854_775_807
let integer: Int = 42 // Platform-specific size
// Floating Point Types
let float: Float = 3.14159
let double: Double = 3.14159265358979
// Boolean
let boolean: Bool = true
// Character and String
let character: Character = "A"
let string: String = "Swift Programming"
Collection Types
Swift
123456789101112// Arrays
var intArray: [Int] = [1, 2, 3]
var emptyArray = [String]()
// Dictionaries
var dict: [String: Int] = ["age": 30, "year": 2023]
var emptyDict = [String: String]()
// Sets
var uniqueInts: Set<Int> = [1, 2, 3, 3, 4]
var emptySet = Set<String>()
Variables and Constants
Swift
123456789101112131415// Constants (immutable)
let pi = 3.14159
let maxLoginAttempts = 3
// Variables (mutable)
var score = 0
score += 10
// Type inference
var name = "Swift" // Inferred as String
var count = 42 // Inferred as Int
// Explicit type annotation
var explicitString: String = "Explicit"
Optionals and Nil Safety
Swift
123456789101112131415// Optional declaration
var optionalName: String? = nil
var definedName: String? = "John"
// Optional binding
if let unwrappedName = optionalName {
print(unwrappedName)
}
// Nil-coalescing operator
let displayName = optionalName ?? "Anonymous"
// Force unwrapping (use with caution)
let forcedValue = optionalName!
Operators
Arithmetic Operators
Swift
123456let sum = 10 + 5
let difference = 10 - 5
let product = 10 * 5
let quotient = 10 / 5
let remainder = 10 % 3
Comparison Operators
Swift
123456789let a = 5
let b = 10
print(a == b) // Equal to
print(a != b) // Not equal to
print(a < b) // Less than
print(a > b) // Greater than
print(a <= b) // Less than or equal to
print(a >= b) // Greater than or equal to
Logical Operators
Swift
123456let x = true
let y = false
print(x && y) // Logical AND
print(x || y) // Logical OR
print(!x) // Logical NOT
Control Structures
Conditional Statements
Swift
123456789101112// If-Else
if condition {
// code
} else if anotherCondition {
// code
} else {
// code
}
// Ternary Conditional
let result = condition ? valueIfTrue : valueIfFalse
Switch Statements
Swift
123456789101112let value = 5
switch value {
case 1:
print("One")
case 2...5:
print("Between two and five")
case let x where x > 10:
print("Greater than ten")
default:
print("Other value")
}
Loops
Swift
1234567891011121314151617// For loop
for i in 1...5 {
print(i)
}
// While loop
var counter = 0
while counter < 5 {
print(counter)
counter += 1
}
// Repeat-While (do-while equivalent)
repeat {
// code
} while condition
Functions
Swift
12345678910111213141516171819202122232425// Basic function
func greet(name: String) -> String {
return "Hello, \(name)!"
}
// Function with multiple parameters
func add(a: Int, b: Int) -> Int {
return a + b
}
// Function with default parameter
func power(base: Int, exponent: Int = 2) -> Int {
return Int(pow(Double(base), Double(exponent)))
}
// Variadic parameters
func sum(_ numbers: Int...) -> Int {
return numbers.reduce(0, +)
}
// Throwing function
func riskyOperation() throws {
// Can throw an error
}
Closures
Swift
123456789// Closure expression
let multiply = { (a: Int, b: Int) -> Int in
return a * b
}
// Trailing closure syntax
let numbers = [1, 2, 3, 4, 5]
let squared = numbers.map { $0 * $0 }
Object-Oriented Programming
Structs
Swift
123456789struct Point {
var x: Double
var y: Double
func distance(to other: Point) -> Double {
return sqrt(pow(x - other.x, 2) + pow(y - other.y, 2))
}
}
Classes
Swift
1234567891011121314class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func introduce() {
print("Hi, I'm \(name)")
}
}
Inheritance
Swift
123456789class Student: Person {
var grade: Int
init(name: String, age: Int, grade: Int) {
self.grade = grade
super.init(name: name, age: age)
}
}
Protocols
Swift
12345678910protocol Drawable {
func draw()
}
struct Circle: Drawable {
func draw() {
print("Drawing a circle")
}
}
Error Handling
Swift
123456789101112131415161718enum NetworkError: Error {
case connectionFailed
case invalidResponse
}
func fetchData() throws {
// Potentially throwing operation
throw NetworkError.connectionFailed
}
do {
try fetchData()
} catch NetworkError.connectionFailed {
print("Connection failed")
} catch {
print("Unknown error")
}
File I/O
Swift
123456789101112import Foundation
// Writing to a file
let content = "Hello, File!"
let fileURL = URL(fileURLWithPath: "/path/to/file.txt")
try? content.write(to: fileURL, atomically: true, encoding: .utf8)
// Reading from a file
if let fileContent = try? String(contentsOf: fileURL, encoding: .utf8) {
print(fileContent)
}
Concurrency
Swift
1234567891011121314// Async/Await
func fetchUserData() async throws -> User {
// Asynchronous operation
}
// Actor for safe concurrent state
actor UserCache {
private var cache = [Int: User]()
func getUser(id: Int) -> User? {
return cache[id]
}
}
Memory Management
Swift
1234567891011// Weak reference to prevent retain cycles
class ViewController {
weak var delegate: ViewControllerDelegate?
}
// Unowned reference
class Customer {
let card: CreditCard
unowned let shop: Shop
}
Testing
Swift
1234567891011121314import XCTest
class MyTests: XCTestCase {
func testAddition() {
XCTAssertEqual(1 + 1, 2)
}
func testPerformance() {
measure {
// Code to measure performance
}
}
}
Popular Frameworks
- SwiftUI: Declarative UI framework
- UIKit: Traditional iOS UI framework
- Combine: Reactive programming framework
- Core Data: Persistence and data management
- Vapor: Server-side Swift framework
- Perfect: Another server-side Swift framework
Best Practices
- Use
letby default,varonly when necessary - Prefer value types (structs) over classes
- Use optionals for potentially absent values
- Leverage type inference
- Use protocol extensions for shared behavior
- Write small, focused functions
- Use guard for early returns and reducing nesting
Resources for Further Learning
- Apple Swift Documentation
- Swift.org
- Ray Wenderlich Tutorials
- Stanford CS193p (iOS Development Course)
- WWDC Swift Sessions
- Swift by Sundell
- Hacking with Swift
Performance Tips
- Use value types when possible
- Avoid excessive dynamic dispatch
- Leverage compile-time optimizations
- Use
@inlinablefor performance-critical code - Profile and optimize with Instruments
Swift Package Manager
Bash
123456789101112# Create a new package
swift package init
# Add a dependency
swift package add-dependency https://github.com/example/library.git
# Build the package
swift build
# Run tests
swift test
Continue Learning
Discover more cheatsheets to boost your productivity