How to create a generic method in Swift

2 Answers

0 votes
// You create a generic method in Swift by adding a type parameter 
// in angle brackets (e.g., <T>) before the parameter list. 

// Swift’s official documentation shows that generics let you write flexible, 
// reusable functions that work with any type. 

// Basic Syntax
// func myFunction<T>(value: T) -> T {
//    return value
// }

// Generic Swap Function
func swapValues<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}

var x = 10
var y = 20
swapValues(&x, &y)

var s1 = "Hello"
var s2 = "World"
swapValues(&s1, &s2)

print(x, y)
print(s1, s2)


/*
run:

20 10
World Hello

*/

 



answered Apr 22 by avibootz
0 votes
// Generic Pair Printer

func printPair<K, V>(_ key: K, _ value: V) {
    print("\(key) = \(value)")
}

printPair("Age", 17)
printPair(101, "Employee ID")
printPair("Pi", 3.14159)


/*
run:

Age = 17
101 = Employee ID
Pi = 3.14159

*/

 



answered Apr 22 by avibootz
...