Protocols, Extensions and Generics

IOS Development 12 min min read Updated: Nov 16, 2026 Intermediate
Protocols, Extensions and Generics
Intermediate Topic 7 of 9

Protocols

A protocol is a contract: a list of properties and methods that a type promises to provide. You have already seen View (it must have a body).

swift protocol Drivable { var speed: Int { get } func drive() } struct Car: Drivable { var speed = 120 func drive() { print("Car drives at \(speed)") } } struct Bike: Drivable { var speed = 25 func drive() { print("Bike rolls at \(speed)") } } let vehicles: [Drivable] = [Car(), Bike()] vehicles.forEach { $0.drive() }

Extensions

Extensions add new features to existing types, even to Apple's own types, without changing their source code.

swift extension String { var isValidEmail: Bool { contains("@") && contains(".") } func capitalizedFirst() -> String { prefix(1).uppercased() + dropFirst() } } print("asha@mail.com".isValidEmail) // true print("swift".capitalizedFirst()) // Swift

Default Implementations

swift extension Drivable { func drive() { print("Moving at \(speed)") } // default behavior }

Protocols You Will Use Every Day

ProtocolMeaningUsed for
IdentifiableHas a stable idList and ForEach rows
EquatableCan be compared with ==Comparing values, onChange
HashableCan be used in sets and as dictionary keysNavigationStack paths, selections
CodableCan be converted to and from JSONNetworking and saving
ComparableCan be sorted with <Sorting custom types
CaseIterableLists all enum casesPickers
swift struct Movie: Identifiable, Codable, Hashable { let id: Int var title: String var year: Int }

Generics

Generics allow one function or type to work with many types. Array<Int> and Array<String> are the same generic type with different parameters.

swift func swapValues<T>(_ a: inout T, _ b: inout T) { let temp = a a = b b = temp } var x = 1, y = 2 swapValues(&x, &y) struct Stack<Element> { private var items: [Element] = [] mutating func push(_ item: Element) { items.append(item) } mutating func pop() -> Element? { items.popLast() } } var stack = Stack<String>() stack.push("a") print(stack.pop() ?? "empty")
swift // Constrain a generic func largest<T: Comparable>(_ list: [T]) -> T? { list.max() }

some View and any

some View means: a specific view type that Swift figures out for me. any Drivable means: any value of a type that conforms to the protocol. Use some for return values like body, and any for mixed collections.

Conclusion

Protocols, extensions and generics make Swift code flexible and reusable. Learn the common protocols, because SwiftUI and Codable rely on them everywhere.

Quick Summary: Protocols are contracts, extensions add features and generics write code for many types. Know Identifiable, Hashable and Codable.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators