Junior — Middle
Kuidas piirata meetodi sees generics-ide lubatud parameetritüüpe?
sobes.tech AI
Vastus AI-lt
In Swift, to restrict the allowed types of parameters in generics within a method, the restriction syntax using protocols or classes is used via the where keyword or inheritance indication.
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 a more complex restriction, 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, restrictions allow the compiler to verify that parameter types meet the specified requirements, increasing code safety and predictability.