Sobes.tech
Junior — Middle

How can you restrict the allowed parameter types in generics inside a method?

sobes.tech AI

Answer from AI

In Swift, to restrict acceptable parameter types in generics within a method, syntax using protocol or class constraints with the where keyword or inheritance is used.

An example of restricting a parameter type to conform to the Equatable protocol:

func findIndex<T: Equatable>(of valueToFind: T, in array: [T]) -> Int? {
    for (index, value) in array.enumerated() {
        if value == valueToFind {
            return index
        }
    }
    return nil
}

For more complex constraints, where can be used:

func compareItems<T, U>(item1: T, item2: U) where T: Comparable, T == U {
    if item1 < item2 {
        print("item1 is less than item2")
    }
}

Thus, constraints allow the compiler to verify that parameter types meet specified requirements, increasing code safety and predictability.