Swift Cheat Sheet
Use this Swift cheat sheet as a quick reference for syntax, variables, data types, strings, collections, functions, closures, optionals, structs, classes, protocols, enums, error handling, async code, and common Swift patterns.
Basic Swift Syntax
Swift code can run in Xcode, Swift Playgrounds, or a Swift project.
Learn Swift on Mimo
Swift
print("Hello, Swift")
Syntax Basics
- Use
letfor constants. - Use
varfor values that can change. - Swift is type-safe.
- Swift uses type inference when the type is clear.
- Statements do not need semicolons.
- Code blocks use curly braces.
Comments
Single-Line Comment
Swift
// This is a single-line comment
Multi-Line Comment
Swift
/*
This comment can span
multiple lines.
*/
Use comments to explain why code exists, especially when the reason is not obvious.
Constants and Variables
Constant with let
Use let when the value should not change.
Swift
let appName = "Mimo"
let maxAttempts = 3
Variable with var
Use var when the value needs to change.
Swift
var score = 0
score += 10
print(score)
Type Annotation
Swift can infer types, but you can also write them explicitly.
Swift
let username: String = "Alex"
let age: Int = 28
let isActive: Bool = true
Use type annotations when they make code clearer or when Swift cannot infer the type.
Basic Data Types
String
Swift
let name: String = "Alex"
Int
Swift
let age: Int = 28
Double
Swift
let price: Double = 19.99
Float
Swift
let progress: Float = 0.75
Bool
Swift
let isLoggedIn: Bool = true
Character
Swift
let grade: Character = "A"
Type Inference
Swift often detects the type from the value.
Swift
let name = "Alex"
let age = 28
let price = 19.99
let isActive = true
Swift understands:
nameis aString.ageis anInt.priceis aDouble.isActiveis aBool.
Add a type when you need a specific one.
Swift
let progress: Float = 0.75
Strings
Create a String
Swift
let greeting = "Hello"
String Interpolation
Use \() to insert values into a string.
Swift
let name = "Alex"
let message = "Hello, \(name)"
print(message)
Multiline String
Swift
let text = """
Line one
Line two
Line three
"""
String Length
Swift
let language = "Swift"
print(language.count)
Change Case
Swift
let text = "Swift"
print(text.lowercased())
print(text.uppercased())
Check Text
Swift
let title = "Learn Swift"
print(title.contains("Swift"))
print(title.hasPrefix("Learn"))
print(title.hasSuffix("Swift"))
Split a String
Swift
let tags = "swift,ios,xcode"
let tagList = tags.split(separator: ",")
print(tagList)
Join Strings
Swift
let words = ["Learn", "Swift"]
let sentence = words.joined(separator: " ")
print(sentence)
Numbers and Math
Basic Math
Swift
let a = 10
let b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
Integer division removes the decimal part.
Swift
print(10 / 3)
For decimal results, use Double.
Swift
let result = 10.0 / 3.0
print(result)
Remainder
Swift
let remainder = 10 % 3
print(remainder)
Convert Number Types
Swift
let count = 5
let price = 19.99
let total = Double(count) * price
print(total)
Swift does not automatically mix numeric types. Convert them when needed.
Operators
Assignment
Swift
var score = 10
score += 5
score -= 2
score *= 3
score /= 2
Comparison
Swift
print(10 == 10)
print(10 != 5)
print(10 > 5)
print(10 >= 10)
print(5 < 10)
print(5 <= 5)
Logical Operators
Swift
let isAdult = true
let hasTicket = false
print(isAdult && hasTicket)
print(isAdult || hasTicket)
print(!isAdult)
Range Operators
Closed range includes the end value.
Swift
for number in 1...5 {
print(number)
}
Half-open range excludes the end value.
Swift
for number in 1..<5 {
print(number)
}
Conditionals
if
Swift
let age = 20
if age >= 18 {
print("Adult")
}
if...else
Swift
let isLoggedIn = false
if isLoggedIn {
print("Welcome back")
} else {
print("Please log in")
}
else if
Swift
let score = 85
if score >= 90 {
print("A")
} else if score >= 80 {
print("B")
} else {
print("Keep practicing")
}
Switch Statements
Use switch to compare a value against multiple cases.
Swift
let role = "admin"
switch role {
case "admin":
print("Full access")
case "editor":
print("Edit access")
default:
print("Read access")
}
Switch with Ranges
Swift
let score = 82
switch score {
case 90...100:
print("A")
case 80..<90:
print("B")
case 70..<80:
print("C")
default:
print("Keep practicing")
}
Swift switch statements must cover all possible values. Use default when needed.
Loops
for...in
Swift
let languages = ["Swift", "JavaScript", "Python"]
for language in languages {
print(language)
}
Loop Through a Range
Swift
for number in 1...5 {
print(number)
}
while
Swift
var count = 0
while count < 3 {
print(count)
count += 1
}
repeat...while
Runs at least once.
Swift
var count = 0
repeat {
print(count)
count += 1
} while count < 3
Loop with Index
Swift
let names = ["Alex", "Sam", "Taylor"]
for (index, name) in names.enumerated() {
print("\(index): \(name)")
}
Break and Continue
Swift
for number in 1...10 {
if number == 5 {
break
}
print(number)
}
Swift
for number in 1...5 {
if number == 3 {
continue
}
print(number)
}
Arrays
Arrays store ordered values.
Swift
let fruits = ["apple", "banana", "orange"]
Array Type Annotation
Swift
let names: [String] = ["Alex", "Sam", "Taylor"]
let scores: [Int] = [90, 85, 100]
Create an Empty Array
Swift
var items: [String] = []
Access Items
Swift
let fruits = ["apple", "banana", "orange"]
print(fruits[0])
print(fruits[1])
Add Items
Swift
var fruits = ["apple", "banana"]
fruits.append("orange")
fruits += ["mango"]
print(fruits)
Change an Item
Swift
var fruits = ["apple", "banana"]
fruits[1] = "mango"
print(fruits)
Remove Items
Swift
var fruits = ["apple", "banana", "orange"]
fruits.remove(at: 1)
fruits.removeLast()
print(fruits)
Array Count
Swift
let fruits = ["apple", "banana", "orange"]
print(fruits.count)
Check If Empty
Swift
let items: [String] = []
if items.isEmpty {
print("No items")
}
Array Methods
Map
Swift
let numbers = [1, 2, 3]
let doubled = numbers.map { number in
number * 2
}
print(doubled)
Short version:
Swift
let doubled = numbers.map { $0 * 2 }
Filter
Swift
let numbers = [1, 2, 3, 4, 5]
let evenNumbers = numbers.filter { number in
number % 2 == 0
}
print(evenNumbers)
Reduce
Swift
let prices = [10, 20, 30]
let total = prices.reduce(0) { sum, price in
sum + price
}
print(total)
Short version:
Swift
let total = prices.reduce(0, +)
Sort
Swift
var numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers)
Create a sorted copy:
Swift
let numbers = [3, 1, 4, 2]
let sortedNumbers = numbers.sorted()
print(sortedNumbers)
Dictionaries
Dictionaries store key-value pairs.
Swift
let user = [
"name": "Alex",
"role": "Developer"
]
Dictionary Type Annotation
Swift
var scores: [String: Int] = [
"Alex": 90,
"Sam": 85
]
Create an Empty Dictionary
Swift
var users: [String: String] = [:]
Access a Value
Dictionary access returns an optional.
Swift
let scores = [
"Alex": 90,
"Sam": 85
]
let alexScore = scores["Alex"]
print(alexScore)
Add or Update a Value
Swift
var scores = [
"Alex": 90
]
scores["Sam"] = 85
scores["Alex"] = 95
print(scores)
Remove a Value
Swift
var scores = [
"Alex": 90,
"Sam": 85
]
scores.removeValue(forKey: "Sam")
print(scores)
Loop Through a Dictionary
Swift
let scores = [
"Alex": 90,
"Sam": 85
]
for (name, score) in scores {
print("\(name): \(score)")
}
Sets
Sets store unique unordered values.
Swift
var tags: Set<String> = ["swift", "ios", "swift"]
print(tags)
Add and Remove
Swift
var tags: Set<String> = ["swift", "ios"]
tags.insert("xcode")
tags.remove("ios")
print(tags)
Check Membership
Swift
let tags: Set<String> = ["swift", "ios"]
print(tags.contains("swift"))
Set Operations
Swift
let a: Set = ["swift", "ios", "xcode"]
let b: Set = ["swift", "macos"]
print(a.union(b))
print(a.intersection(b))
print(a.subtracting(b))
Use sets when uniqueness matters more than order.
Functions
Define a Function
Swift
func greet(name: String) -> String {
return "Hello, \(name)"
}
print(greet(name: "Alex"))
Function with No Return Value
Swift
func logMessage(_ message: String) {
print(message)
}
logMessage("Task complete")
External and Internal Parameter Names
Swift
func greet(person name: String) {
print("Hello, \(name)")
}
greet(person: "Alex")
person is the external name. name is used inside the function.
Omit External Parameter Name
Swift
func square(_ number: Int) -> Int {
return number * number
}
print(square(5))
Default Parameter Value
Swift
func greet(name: String = "Guest") {
print("Hello, \(name)")
}
greet()
greet(name: "Alex")
Return Multiple Values
Use a tuple to return more than one value.
Swift
func getUser() -> (name: String, age: Int) {
return ("Alex", 28)
}
let user = getUser()
print(user.name)
print(user.age)
You can also destructure the tuple.
Swift
let (name, age) = getUser()
print(name)
print(age)
Closures
Closures are reusable blocks of code.
Swift
let greet = { (name: String) -> String in
return "Hello, \(name)"
}
print(greet("Alex"))
Closure as a Function Argument
Swift
let numbers = [1, 2, 3]
let doubled = numbers.map { number in
number * 2
}
print(doubled)
Shorthand Closure Arguments
Swift
let numbers = [1, 2, 3]
let doubled = numbers.map { $0 * 2 }
print(doubled)
Use shorthand when the closure stays easy to read.
Optionals
An optional can hold a value or nil.
Swift
var username: String? = "Alex"
username = nil
Use optionals when a value may be missing.
Optional Type
Swift
let email: String? = nil
String? means the value is either a String or nil.
Optional Binding
Use if let to unwrap an optional safely.
Swift
let email: String? = "alex@example.com"
if let email = email {
print(email)
} else {
print("No email")
}
guard let
Use guard let when you want to exit early if a value is missing.
Swift
func sendEmail(to email: String?) {
guard let email = email else {
print("Missing email")
return
}
print("Sending email to \(email)")
}
guard keeps the successful path less nested.
Nil Coalescing
Use ?? to provide a fallback value.
Swift
let username: String? = nil
let displayName = username ?? "Guest"
print(displayName)
This uses "Guest" only when username is nil.
Optional Chaining
Use optional chaining to access properties or methods on optional values.
Swift
struct Profile {
let email: String
}
struct User {
let profile: Profile?
}
let user = User(profile: nil)
print(user.profile?.email)
If profile is nil, the result is nil instead of a crash.
Force Unwrapping
Force unwrapping uses !.
Swift
let email: String? = "alex@example.com"
print(email!)
Only force unwrap when you are certain the optional has a value. If it is nil, the app crashes.
Safer:
Swift
if let email = email {
print(email)
}
Structs
Structs define custom value types.
Swift
struct User {
let name: String
var age: Int
}
let user = User(name: "Alex", age: 28)
print(user.name)
Add a Method
Swift
struct User {
let name: String
func greet() -> String {
return "Hello, \(name)"
}
}
let user = User(name: "Alex")
print(user.greet())
Mutating Method
Use mutating when a struct method changes its own properties.
Swift
struct Counter {
var count = 0
mutating func increase() {
count += 1
}
}
var counter = Counter()
counter.increase()
print(counter.count)
Classes
Classes define reference types.
Swift
class User {
let name: String
init(name: String) {
self.name = name
}
func greet() -> String {
return "Hello, \(name)"
}
}
let user = User(name: "Alex")
print(user.greet())
Class Inheritance
Swift
class Animal {
func speak() {
print("Sound")
}
}
class Dog: Animal {
override func speak() {
print("Bark")
}
}
let dog = Dog()
dog.speak()
Use override when a subclass changes a superclass method.
Structs vs Classes
Use Structs When:
- You need value semantics.
- You model simple data.
- You do not need inheritance.
- You want copies to be independent.
Use Classes When:
- You need shared reference behavior.
- You need inheritance.
- You work with APIs that require classes.
- You need identity checks.
Most Swift models start well as structs.
Enums
Enums define a fixed set of cases.
Swift
enum Direction {
case up
case down
case left
case right
}
let direction = Direction.up
Switch on an Enum
Swift
switch direction {
case .up:
print("Move up")
case .down:
print("Move down")
case .left:
print("Move left")
case .right:
print("Move right")
}
Enum with Raw Values
Swift
enum Status: String {
case draft = "draft"
case published = "published"
case archived = "archived"
}
print(Status.published.rawValue)
Enum with Associated Values
Swift
enum ResultState {
case loading
case success(data: String)
case failure(message: String)
}
let state = ResultState.success(data: "Loaded")
switch state {
case .loading:
print("Loading")
case .success(let data):
print(data)
case .failure(let message):
print(message)
}
Associated values are useful for states that carry extra data.
Protocols
Protocols define requirements that a type must follow.
Swift
protocol Greetable {
var name: String { get }
func greet() -> String
}
Conform to a protocol:
Swift
struct User: Greetable {
let name: String
func greet() -> String {
return "Hello, \(name)"
}
}
Use protocols to describe shared behavior across different types.
Extensions
Extensions add functionality to an existing type.
Swift
extension String {
func shout() -> String {
return self.uppercased()
}
}
let message = "hello"
print(message.shout())
Extend a Custom Type
Swift
struct User {
let name: String
}
extension User {
func greet() -> String {
return "Hello, \(name)"
}
}
Extensions help organize code without changing the original type definition.
Computed Properties
Computed properties calculate a value.
Swift
struct Rectangle {
let width: Double
let height: Double
var area: Double {
width * height
}
}
let rectangle = Rectangle(width: 10, height: 5)
print(rectangle.area)
Use computed properties when a value can be derived from other properties.
Property Observers
Property observers run when a property changes.
Swift
var score = 0 {
willSet {
print("Score will change to \(newValue)")
}
didSet {
print("Score changed from \(oldValue) to \(score)")
}
}
score = 10
Use observers for side effects tied to property changes.
Access Control
Access control limits where code can be used.
Common Access Levels
openallows subclassing and access outside the module.publicallows access outside the module.internalallows access inside the module and is the default.fileprivateallows access inside the same file.privateallows access inside the enclosing scope.
Private Property
Swift
struct Account {
private var balance: Double = 0
mutating func deposit(_ amount: Double) {
balance += amount
}
}
Use private to protect implementation details.
Error Handling
Define an error type with an enum.
Swift
enum LoginError: Error {
case missingEmail
case invalidPassword
}
Throw an error:
Swift
func login(email: String, password: String) throws {
if email.isEmpty {
throw LoginError.missingEmail
}
if password.count < 8 {
throw LoginError.invalidPassword
}
print("Logged in")
}
Handle errors with do, try, and catch.
Swift
do {
try login(email: "", password: "123")
} catch LoginError.missingEmail {
print("Email is required")
} catch LoginError.invalidPassword {
print("Password is too short")
} catch {
print("Something went wrong")
}
try? and try!
Use try? to convert a thrown result into an optional.
Swift
let result = try? login(email: "alex@example.com", password: "password123")
Use try! only when you are certain the function will not throw.
Swift
try! login(email: "alex@example.com", password: "password123")
If the function throws, try! crashes the app.
Generics
Generics let code work with different types.
Swift
func printValue<T>(_ value: T) {
print(value)
}
printValue("Hello")
printValue(42)
Generic Function That Returns a Value
Swift
func firstItem<T>(from items: [T]) -> T? {
return items.first
}
let firstName = firstItem(from: ["Alex", "Sam"])
let firstNumber = firstItem(from: [1, 2, 3])
Generic Type Constraint
Swift
func printCount<T: Collection>(_ items: T) {
print(items.count)
}
printCount(["Swift", "iOS"])
Use constraints when the generic type must support specific behavior.
Async and Await
Use async and await for asynchronous code.
Swift
func fetchUsername() async -> String {
return "Alex"
}
Call it with await from another async context.
Swift
let username = await fetchUsername()
print(username)
Async Throwing Function
Swift
enum NetworkError: Error {
case failed
}
func fetchData() async throws -> String {
throw NetworkError.failed
}
Handle it with do, try, and await.
Swift
do {
let data = try await fetchData()
print(data)
} catch {
print("Request failed")
}
Tasks
Use Task to start async work from synchronous code.
Swift
Task {
let username = await fetchUsername()
print(username)
}
This is common in SwiftUI views and app code that needs to call async functions.
Main Actor
Use @MainActor for code that updates UI state.
Swift
@MainActor
func updateUI() {
print("Update UI on the main actor")
}
In SwiftUI, UI-related state often updates on the main actor.
SwiftUI Basics
SwiftUI uses structs to define views.
Swift
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, SwiftUI")
}
}
VStack
Swift
VStack {
Text("Title")
Text("Subtitle")
}
HStack
Swift
HStack {
Text("Left")
Text("Right")
}
Button
Swift
Button("Tap me") {
print("Tapped")
}
State
Swift
import SwiftUI
struct CounterView: View {
@State private var count = 0
var body: some View {
Button("Count: \(count)") {
count += 1
}
}
}
Use @State for local view state.
Common Swift Patterns
Safe Optional Handling
Swift
func displayName(_ name: String?) -> String {
guard let name = name else {
return "Guest"
}
return name
}
Filter an Array
Swift
let users = [
"Alex",
"Sam",
"Taylor"
]
let filteredUsers = users.filter { user in
user.hasPrefix("A")
}
print(filteredUsers)
Find an Item
Swift
let numbers = [1, 2, 3, 4]
let firstEven = numbers.first { number in
number % 2 == 0
}
print(firstEven)
Group State with an Enum
Swift
enum ViewState {
case loading
case loaded(items: [String])
case failed(message: String)
}
let state = ViewState.loaded(items: ["Swift", "iOS"])
Format a Simple Model
Swift
struct Course {
let title: String
let lessonCount: Int
var summary: String {
"\(title): \(lessonCount) lessons"
}
}
let course = Course(title: "Swift Basics", lessonCount: 12)
print(course.summary)
Common Mistakes
Using var When let Is Enough
Swift
var name = "Alex"
Better:
Swift
let name = "Alex"
Use let by default. Switch to var only when the value needs to change.
Force Unwrapping Too Early
Swift
let email: String? = nil
print(email!)
Better:
Swift
if let email = email {
print(email)
} else {
print("No email")
}
Force unwrapping a nil value crashes the app.
Changing a let Constant
Swift
let score = 10
score = 20
Better:
Swift
var score = 10
score = 20
Use var only when reassignment is required.
Forgetting mutating in a Struct
Swift
struct Counter {
var count = 0
func increase() {
count += 1
}
}
Better:
Swift
struct Counter {
var count = 0
mutating func increase() {
count += 1
}
}
Struct methods need mutating when they change stored properties.
Mixing Numeric Types
Swift
let count = 3
let price = 19.99
let total = count * price
Better:
Swift
let count = 3
let price = 19.99
let total = Double(count) * price
Swift does not automatically multiply Int and Double.
Debugging Tips
Print Values
Swift
print(user)
Print Labels
Swift
print("Current user:", user)
Check Optional Values
Swift
let email: String? = nil
print(email as Any)
Casting to Any can silence optional print warnings when you are debugging.
Use Breakpoints in Xcode
Set a breakpoint by clicking the line number area in Xcode. Run the app, then inspect variables when execution pauses.
Read Error Messages Carefully
Swift errors often tell you:
- Which type Swift expected
- Which type you provided
- Which value may be optional
- Which function needs
try - Which async call needs
await
Quick Reference
Print Output
Swift
print("Hello")
Create a Constant
Swift
let name = "Alex"
Create a Variable
Swift
var count = 0
Create an Array
Swift
let items = ["one", "two", "three"]
Create a Dictionary
Swift
let user = [
"name": "Alex",
"role": "Developer"
]
Create a Function
Swift
func greet(name: String) -> String {
return "Hello, \(name)"
}
Create an Optional
Swift
let email: String? = nil
Unwrap an Optional
Swift
if let email = email {
print(email)
}
Use a Guard Statement
Swift
guard let email = email else {
return
}
Create a Struct
Swift
struct User {
let name: String
}
Create a Class
Swift
class User {
let name: String
init(name: String) {
self.name = name
}
}
Create an Enum
Swift
enum Status {
case loading
case success
case failure
}
Create a Protocol
Swift
protocol Greetable {
func greet() -> String
}
Handle Errors
Swift
do {
try riskyFunction()
} catch {
print(error)
}
Use Async Code
Swift
Task {
let result = await loadData()
print(result)
}
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot