Swift Documentation
Apple's fast, safe language for iOS, macOS and SwiftUI apps.
Swift is Apple's modern, fast and safe language for building apps on iPhone, iPad, Mac, Apple Watch and Apple TV. It replaced Objective-C, has clean syntax, strong type inference, optionals for null safety, value types (structs) and modern concurrency with async/await. With SwiftUI you build interfaces declaratively.
1. Introduction & Installation
- macOS: install Xcode from the App Store — it includes Swift, the iOS simulator and SwiftUI previews. Start with a Playground to experiment.
- Linux/Windows: download the toolchain from swift.org/install (good for learning the language and server-side Swift).
swift --version
swift hello.swift # run a script
swiftc hello.swift -o hello && ./hello # compile to an executable
swift package init --type executable # new SwiftPM project
print("Hello, Codify!")
Output:
Hello, Codify!
⚠️ Common error: iOS apps can only be built and signed on a Mac with Xcode. On Windows/Linux you can learn Swift itself, but not ship iOS apps.
2. Basic Syntax
- No
mainfunction needed in scripts — top-level code runs in order. - Semicolons are optional.
let= constant,var= variable. - String interpolation:
"\(expression)".
let name = "Asha"
var score = 90
score += 5
print("\(name) scored \(score)")
print("Next level at \(score + 10) points")
print("A", "B", "C", separator: "-")
Output:
Asha scored 95
Next level at 105 points
A-B-C
⚠️ Common error:
Cannot assign to value: 'x' is a 'let' constant— declare it withvarif it must change (Swift encouragesletby default).
3. Variables & Data Types
| Type | Example |
|---|---|
Int |
let n = 42 |
Double, Float |
let pi = 3.14 (Double by default) |
Bool |
true, false |
String, Character |
"Swift", "S" |
| optionals | String? — a value or nil |
| tuples | (404, "Not Found") |
let count: Int = 10
let price = 99.5 // Double
let isOpen = true
let grade: Character = "A"
let status = (code: 404, message: "Not Found")
var nickname: String? = nil // optional
print(count, price, isOpen, grade)
print(status.code, status.message)
print(nickname ?? "no nickname") // nil-coalescing
nickname = "Ash"
if let nick = nickname { // optional binding (safe unwrap)
print("Nickname is \(nick)")
}
print(Int("42")! + 1, Double(7) / 2, Int(9.9), 7 / 2)
Output:
10 99.5 true A
404 Not Found
no nickname
Nickname is Ash
43 3.5 9 3
⚠️ Common error:
Fatal error: Unexpectedly found nil while unwrapping an Optional value— you force-unwrapped (!) anil. Useif let,guard letor??.
4. Operators
Arithmetic + - * / %, comparison == != < > <= >=, logical && || !, ranges a...b (closed) and a..<b (half-open), nil-coalescing ??, ternary ?:, identity === for class instances. Swift has no ++/--; use += 1. Integer overflow traps at runtime (use &+ for wrapping).
let a = 17, b = 5
print(a / b, a % b, Double(a) / Double(b))
print(a > b && b > 0, !(a == 17))
print((1...5).contains(5), (1..<5).contains(5))
print(6 & 3, 6 | 3, 6 ^ 3, 1 << 10)
let max = a > b ? a : b
print(max)
Output:
3 2 3.4
true false
true false
2 7 5 1024
17
⚠️ Common error:
Binary operator '+' cannot be applied to operands of type 'Int' and 'Double'— Swift never converts numbers implicitly. Convert:Double(a) + d.
5. Conditional Statements
func grade(_ marks: Int) -> String {
if marks >= 90 { return "A" }
else if marks >= 75 { return "B" }
return "C"
}
print(grade(82))
let point = (0, -3)
switch point { // switch must be exhaustive; no fall-through
case (0, 0):
print("origin")
case (0, let y):
print("on y-axis at \(y)")
case (let x, 0):
print("on x-axis at \(x)")
default:
print("elsewhere")
}
let temp = 31
switch temp {
case ..<15: print("cold")
case 15..<26: print("pleasant")
default: print("hot")
}
func divide(_ a: Int, by b: Int) -> Int? {
guard b != 0 else { return nil } // early exit
return a / b
}
print(divide(10, by: 2) ?? -1, divide(1, by: 0) ?? -1)
Output:
B
on y-axis at -3
hot
5 -1
⚠️ Common error:
Switch must be exhaustive— add adefaultcase (or cover every enum case).
6. Loops
for i in 1...5 { print(i, terminator: " ") }
print()
for i in stride(from: 10, through: 0, by: -3) { print(i, terminator: " ") }
print()
let langs = ["swift", "kotlin", "dart"]
for (index, lang) in langs.enumerated() { print(index, lang) }
var n = 1
while n < 100 { n *= 3 }
print("n =", n)
var k = 0
repeat { k += 1 } while k < 3 // like do-while
print("k =", k)
for i in 1...10 where i % 4 == 0 { print(i, terminator: " ") }
print()
Output:
1 2 3 4 5
10 7 4 1
0 swift
1 kotlin
2 dart
n = 243
k = 3
4 8
⚠️ Common error:
1...0crashes ("Range requires lowerBound <= upperBound"). Usestridefor counting down or guard empty ranges.
7. Functions
Functions use argument labels for readability. Use _ to omit a label.
func greet(_ name: String, with greeting: String = "Hello") -> String {
return "\(greeting), \(name)!"
}
func minMax(_ numbers: [Int]) -> (min: Int, max: Int)? { // returns an optional tuple
guard let first = numbers.first else { return nil }
var lo = first, hi = first
for x in numbers { lo = min(lo, x); hi = Swift.max(hi, x) }
return (lo, hi)
}
func sum(_ nums: Int...) -> Int { nums.reduce(0, +) } // variadic, implicit return
func doubleInPlace(_ x: inout Int) { x *= 2 } // inout = pass by reference
func makeCounter() -> () -> Int { // closure capturing state
var count = 0
return { count += 1; return count }
}
print(greet("Asha"), greet("Ravi", with: "Namaste"))
if let r = minMax([4, -2, 9]) { print(r.min, r.max) }
var v = 7
doubleInPlace(&v)
let next = makeCounter()
_ = next()
print(sum(1, 2, 3, 4), v, next())
let squares = [1, 2, 3].map { $0 * $0 } // trailing closure, $0 shorthand
print(squares)
Output:
Hello, Asha! Namaste, Ravi!
-2 9
10 14 2
[1, 4, 9]
⚠️ Common error:
Missing argument label 'with:' in call— include the external labels exactly as declared.
8. Arrays & Data Structures
Arrays, dictionaries and sets are value types (copied on assignment).
var nums = [5, 3, 8, 1]
nums.append(9)
nums.sort()
print(nums, nums.count, nums.first!, nums.contains(8))
print(nums.filter { $0 % 2 == 1 }, nums.map { $0 * 2 }, nums.reduce(0, +))
print(nums.sorted(by: >), Array(nums.prefix(2)), nums.firstIndex(of: 8)!)
var ages: [String: Int] = ["asha": 21, "ravi": 23]
ages["neha"] = 22
print(ages["asha"]!, ages["john", default: 0], ages.count)
for name in ages.keys.sorted() { print(name, ages[name]!) }
let words = "to be or not to be".split(separator: " ")
var freq: [Substring: Int] = [:]
for w in words { freq[w, default: 0] += 1 }
print(freq["to"]!, freq["be"]!, freq["not"]!)
let unique: Set = [3, 1, 3, 2]
print(unique.count, unique.contains(2), unique.sorted())
var grid = Array(repeating: Array(repeating: 0, count: 3), count: 2)
grid[1][2] = 7
print(grid)
Output:
[1, 3, 5, 8, 9] 5 1 true
[1, 3, 5, 9] [2, 6, 10, 16, 18] 26
[9, 8, 5, 3, 1] [1, 3] 3
21 0 3
asha 21
neha 22
ravi 23
2 2 1
3 true [1, 2, 3]
[[0, 0, 0], [0, 0, 7]]
⚠️ Common error:
Index out of rangecrash — always checkindex < array.count(or usearray.indices.contains(i)).
9. Object-Oriented Programming
Swift has structs (value types — preferred for data), classes (reference types with inheritance), enums with associated values, and protocols (like interfaces).
protocol Shape {
var name: String { get }
func area() -> Double
}
extension Shape { // protocol extension: default implementation
func describe() -> String { "\(name) with area \(area())" }
}
struct Rect: Shape {
let w: Double, h: Double
var name: String { "rect" } // computed property
func area() -> Double { w * h }
}
struct Square: Shape {
let side: Double
let name = "square"
func area() -> Double { side * side }
}
class Account {
let owner: String
private(set) var balance: Double // readable outside, settable inside
init(owner: String, balance: Double = 0) {
self.owner = owner
self.balance = balance
}
func deposit(_ amount: Double) { balance += amount }
}
final class Savings: Account { // inheritance
let rate: Double
init(owner: String, balance: Double, rate: Double) {
self.rate = rate
super.init(owner: owner, balance: balance)
}
func addInterest() { deposit(balance * rate) }
}
enum Payment {
case cash
case upi(id: String)
case card(last4: String)
}
let shapes: [Shape] = [Rect(w: 3, h: 4), Square(side: 2)]
for s in shapes { print(s.describe()) }
let acc = Savings(owner: "Asha", balance: 1000, rate: 0.05)
acc.deposit(1000)
acc.addInterest()
print(acc.owner, acc.balance)
let p = Payment.upi(id: "asha@upi")
if case .upi(let id) = p { print("Paid via UPI \(id)") }
Output:
rect with area 12.0
square with area 4.0
Asha 2100.0
Paid via UPI asha@upi
Struct vs class: structs are copied (each variable has its own value), classes are shared references. Methods that change a struct must be marked mutating.
⚠️ Common error:
Cannot use mutating member on immutable value— the struct instance is declared withlet, or the method isn't markedmutating.
10. Advanced Concepts
Error handling with throws, do/try/catch:
enum BankError: Error {
case insufficientFunds(needed: Double)
case invalidAmount
}
func withdraw(_ amount: Double, from balance: Double) throws -> Double {
guard amount > 0 else { throw BankError.invalidAmount }
guard amount <= balance else { throw BankError.insufficientFunds(needed: amount - balance) }
return balance - amount
}
do {
print(try withdraw(30, from: 100))
print(try withdraw(150, from: 100))
} catch BankError.insufficientFunds(let needed) {
print("Need \(needed) more")
} catch {
print("Other error: \(error)")
}
let maybe = try? withdraw(-5, from: 10) // nil on error
print(maybe == nil)
70.0
Need 50.0 more
true
Generics:
struct Stack<Element> {
private var items: [Element] = []
mutating func push(_ x: Element) { items.append(x) }
mutating func pop() -> Element? { items.popLast() }
var top: Element? { items.last }
}
func largest<T: Comparable>(_ a: T, _ b: T) -> T { a > b ? a : b }
var st = Stack<String>()
st.push("a"); st.push("b")
print(st.pop()!, st.top!, largest(3, 9), largest("apple", "mango"))
b a 9 mango
Closures and higher-order functions — map, filter, reduce, compactMap, sorted(by:):
let raw = ["4", "x", "15", "8"]
let numbers = raw.compactMap { Int($0) } // drops values that fail to convert
print(numbers, numbers.sorted { $0 > $1 }, numbers.reduce(0) { $0 + $1 })
[4, 15, 8] [15, 8, 4] 27
Concurrency with async/await:
func fetchUser(id: Int) async throws -> String {
try await Task.sleep(nanoseconds: 100_000_000) // e.g. a network call
return "user\(id)"
}
Task {
async let a = fetchUser(id: 1)
async let b = fetchUser(id: 2)
let users = try await [a, b] // both run in parallel
print(users)
}
SwiftUI fundamentals — UI is a function of state:
import SwiftUI
struct CounterView: View {
@State private var count = 0
var body: some View {
VStack(spacing: 16) {
Text("Count: \(count)")
.font(.largeTitle)
Button("Tap me") { count += 1 }
.buttonStyle(.borderedProminent)
}
.padding()
}
}
Key SwiftUI ideas: View structs, modifiers (.padding(), .font()), state with @State, @Binding, @Observable/@StateObject, layout with VStack/HStack/ZStack/List, and navigation with NavigationStack.
11. Examples with Output
Example 1 — Palindrome check
func isPalindrome(_ s: String) -> Bool {
let clean = s.lowercased().filter { $0.isLetter || $0.isNumber }
return clean == String(clean.reversed())
}
print(isPalindrome("A man, a plan, a canal: Panama"), isPalindrome("Swift"))
true false
Example 2 — Two Sum with a dictionary
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var seen: [Int: Int] = [:]
for (i, x) in nums.enumerated() {
if let j = seen[target - x] { return [j, i] }
seen[x] = i
}
return []
}
print(twoSum([2, 7, 11, 15], 9))
[0, 1]
Example 3 — Grouping with Dictionary(grouping:)
struct Student { let name: String; let dept: String; let marks: Int }
let students = [Student(name: "Asha", dept: "CSE", marks: 91),
Student(name: "Ravi", dept: "ECE", marks: 78),
Student(name: "Neha", dept: "CSE", marks: 85)]
let byDept = Dictionary(grouping: students, by: { $0.dept })
for dept in byDept.keys.sorted() {
let names = byDept[dept]!.map { $0.name }.joined(separator: ", ")
print("\(dept): \(names)")
}
CSE: Asha, Neha
ECE: Ravi
12. Practice Problems
- Write
func isPrime(_ n: Int) -> Booland print primes below 50. - Count vowels in a string using
filter. - Create a
struct BankAccountwithmutatingdeposit/withdraw that throws on insufficient funds. - Model app screens with an
enum Screenthat has associated values (e.g..profile(userId:)). - Implement a generic
Queue<T>withenqueue,dequeueandisEmpty. - Fetch two values concurrently with
async let. - Build a SwiftUI to-do list: add, delete and mark items done.
- Solve the logic of Two Sum and Valid Parentheses in Swift (submit in C++/Java/Python on Codify).
13. Interview Questions
1. What are optionals?
A type that holds either a value or nil (String?). They must be unwrapped safely with if let, guard let, ?? or optional chaining.
2. struct vs class?
Structs are value types (copied, no inheritance, stack-friendly); classes are reference types with inheritance, deinitializers and identity (===).
3. let vs var?
let declares a constant, var a variable. For a struct declared with let, its properties can't change either.
4. What is a protocol? A blueprint of methods/properties that types adopt; with protocol extensions it provides default behaviour — Swift is "protocol-oriented".
5. guard vs if let?
guard let unwraps and exits early if nil, keeping the unwrapped value available for the rest of the scope; if let scopes it to the if-block.
6. What is ARC?
Automatic Reference Counting frees class instances when no strong references remain. Retain cycles are broken with weak or unowned references.
7. What is @escaping?
Marks a closure parameter that may be called after the function returns (e.g. stored or used asynchronously).
8. What does mutating mean?
A struct/enum method that modifies self must be marked mutating.
9. How does error handling work?
Functions marked throws can throw values conforming to Error; callers use try inside do/catch, or try?/try!.
10. What is @State in SwiftUI?
A property wrapper that stores view-local state; when it changes, SwiftUI re-renders the view's body.
14. Cheat Sheet & References
Basics
let x = 5; var y = 10
print("x = \(x)", terminator: "\n")
let n = Int(readLine()!)!
var name: String? = nil; name ?? "guest"; name?.count
if let n = name { } guard let n = name else { return }
Control flow
if a > b { } else { }
switch x { case 1, 2: break; case 3..<10: break; default: break }
for i in 0..<n { } for i in stride(from: n, to: 0, by: -1) { }
while cond { } repeat { } while cond
Collections
var a = [1, 2]; a.append(3); a.remove(at: 0); a.count; a.isEmpty
a.sorted(); a.map { $0 * 2 }; a.filter { $0 > 1 }; a.reduce(0, +)
var d = ["k": 1]; d["k"] = 2; d["z", default: 0]; d.keys.sorted()
var s: Set = [1, 2]; s.insert(3); s.contains(1)
Functions and closures
func add(_ a: Int, to b: Int = 0) -> Int { a + b }
let sq: (Int) -> Int = { $0 * $0 }
func run(_ f: @escaping () -> Void) { }
Types
struct P { var x: Int; mutating func move() { x += 1 } }
class A { init() {} }; class B: A { override init() { super.init() } }
enum E { case a, b(Int) }
protocol Named { var name: String { get } }
extension Int { var squared: Int { self * self } }
Errors and async
enum MyError: Error { case bad }
func f() throws { throw MyError.bad }
do { try f() } catch { print(error) }
func load() async throws -> Data { try await URLSession.shared.data(from: url).0 }
Official documentation