Generic Constraints in Swift

From the Swift cheat sheet · Generics (Advanced) · verified Jul 2026

Generic Constraints

Advanced generic type relationships

swift
// Generic function with multiple constraints
func findDuplicates<T: Hashable & Comparable>(in array: [T]) -> [T] {
    var seen = Set<T>()
    var duplicates = Set<T>()

    for item in array {
        if !seen.insert(item).inserted {
            duplicates.insert(item)
        }
    }

    return duplicates.sorted()
}

// Associated type constraints
protocol DataProvider {
    associatedtype DataType: Codable & Equatable
    func fetchData() -> DataType
}

// Generic class with constraints
class Cache<Key: Hashable, Value> {
    private var storage = [Key: Value]()

    func store(_ value: Value, for key: Key) {
        storage[key] = value
    }

    func retrieve(for key: Key) -> Value? {
        return storage[key]
    }
}
💡 Multiple constraints can be combined with &
⚡ Associated types with constraints enable powerful abstractions
📌 Conditional methods appear only when constraints are satisfied
🟢 Opaque types (some) hide implementation details while preserving type
Back to the full Swift cheat sheet