Swift — Generics
Generic functions
func swapTwo<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
var x = 1, y = 2
swapTwo(&x, &y)
print(x, y) // 2 1
Generic types
struct Stack<Element> {
private var items: [Element] = []
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element? {
items.popLast()
}
var count: Int { items.count }
}
var stack = Stack<Int>()
stack.push(1)
stack.push(2)
print(stack.pop() ?? 0) // 2
Type constraints
func findIndex<T: Equatable>(of value: T, in array: [T]) -> Int? {
for (index, item) in array.enumerated() {
if item == value {
return index
}
}
return nil
}
print(findIndex(of: 3, in: [1, 2, 3, 4])) // Optional(2)
Where clause
func process<T, U>(a: T, b: U) where T: Numeric, U: CustomStringConvertible {
print("\(a) - \(b)")
}
process(a: 42, b: "hello")
Associated types
protocol Container {
associatedtype Item
mutating func push(_ item: Item)
mutating func pop() -> Item?
}
Mini Practice
Write Swift code that:
- Creates a generic
Stackstruct - Writes a generic function with type constraints
- Uses a
whereclause - Defines a protocol with an associated type
Up Next
Congratulations! You've completed the Swift fundamentals. Continue exploring advanced topics like SwiftUI, Combine, and async/await.
Related Topics
Frequently Asked Questions about Generics
What is Generics in Swift?
Generics is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Generics?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Generics.
Why is Generics important in Swift?
Generics is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.