Junior — Middle
Is it possible to implement a universal function using templates in programming?
sobes.tech AI
Answer from AI
Yes, in programming, it is possible to implement a universal function using templates (generics). This allows creating functions that work with different data types while maintaining type safety.
In Swift (iOS), this is done using generic functions:
func swapValues<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
var x = 5
var y = 10
swapValues(&x, &y) // x is now 10, y is now 5
var s1 = "Hello"
var s2 = "World"
swapValues(&s1, &s2) // s1 is now "World", s2 is now "Hello"
Here, T is a type parameter that allows the function to work with any type passed to it. Thus, templates enable writing reusable and type-safe code.