Five common Generics use-cases in Swift

Rahul Goel
2 min readMay 23, 2023

--

Here are five common examples of using generics in Swift:

1. Array Sorting: The `sort` function in Swift’s standard library uses generics to allow sorting of arrays containing elements of any comparable type.

func sort<T: Comparable>(_ array: inout [T]) {
array.sort()
}

var numbers = [4, 2, 1, 3]
sort(&numbers)
print(numbers) // Output: [1, 2, 3, 4]

2. Stack Data Structure: Generics can be used to create a generic stack data structure that can store elements of any type.

struct Stack<T> {
private var elements = [T]()

mutating func push(_ element: T) {
elements.append(element)
}

mutating func pop() -> T? {
return elements.popLast()
}
}
var stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) // Output: Optional(3)

3. Optional Unwrapping: Generics can simplify optional unwrapping by providing a generic function that safely unwraps an optional value or returns a default value.

func unwrap<T>(_ optional: T?, default defaultValue: T) -> T {
return optional ?? defaultValue
}
let name: String? = “John”
let unwrappedName = unwrap(name, default: “Unknown”)
print(unwrappedName) // Output: “John”

4. Dictionary with Default Value: Generics can be used to create a dictionary that returns a default value when accessing a key that doesn’t exist.

struct DefaultDictionary<Key: Hashable, Value> {
private var dictionary = [Key: Value]()
private let defaultValue: Value

init(defaultValue: Value) {
self.defaultValue = defaultValue
}

subscript(key: Key) -> Value {
get {
return dictionary[key] ?? defaultValue
}
set {
dictionary[key] = newValue
}
}
}
var scores = DefaultDictionary<Int, Int>(defaultValue: 0)
scores[1] = 10
print(scores[1]) // Output: 10
print(scores[2]) // Output: 0 (default value)

5. Custom Equatable: Generics can be used to create a generic function that checks if two values of any type are equal using the `Equatable` protocol.

func areEqual<T: Equatable>(_ a: T, _ b: T) -> Bool {
return a == b
}
let a = 5
let b = 5
print(areEqual(a, b)) // Output: true

These examples showcase the versatility and power of generics in Swift, allowing you to write reusable and type-safe code for various scenarios.

Follow me Rahul Goel for more updates.

--

--

Rahul Goel
Rahul Goel

Written by Rahul Goel

Computer Science Enthusiast | 11+ Year of Software Evolution | @Sharechat, Groupon, Paytm, Myntra https://www.linkedin.com/in/therahulgoel/

Responses (1)