Ans :
Apple doc says: Generic code enables you to write flexible, reusable functions and types that can work with any type. You can write code that avoids duplication by using generics in most cases.
Code for Example :
If we want to print all values, we have to make 2 functions accepting integer array or string array.
But using Generic, we can make 1 method accepting generic type.
<T> after the function name represents a generic function. A generic function can work with whatever type. We can put whatever instead of T. T is placeholder type. We can use for dictionary like Dictionary<key,value> and for array like Array<element> .
Generic function with parameter type :
In above methods, we use different placeholder type in method1 and same placeholder type in method2. If out passing parameter types are different then 2nd method will be called, and if same then 1st method will be called.
Generic function with type constraints :
Sometimes, we require specific types only i.e type which confirm comparable protocol
Apple doc says: Generic code enables you to write flexible, reusable functions and types that can work with any type. You can write code that avoids duplication by using generics in most cases.
Code for Example :
let intArray = [1,2,3,4,5] // type int
let stringArray = [“abhi”, “iOS”] // type string
If we want to print all values, we have to make 2 functions accepting integer array or string array.
But using Generic, we can make 1 method accepting generic type.
func printAnyArray<T>(arr:[T]) {
arr.map { print($0) }
}
<T> after the function name represents a generic function. A generic function can work with whatever type. We can put whatever instead of T. T is placeholder type. We can use for dictionary like Dictionary<key,value> and for array like Array<element> .
Generic function with parameter type :
//Declare
func anotherMethod<T, U> (first: T, second: U) { print("first one called")}
func anotherMethod<T> (first: T, second: T) { print("second one called")}
//Call
anotherMethod(first: 123, second: "456") // T - Int, U - String
anotherMethod(first: 123, second: 456) // T - Int
In above methods, we use different placeholder type in method1 and same placeholder type in method2. If out passing parameter types are different then 2nd method will be called, and if same then 1st method will be called.
Generic function with type constraints :
func middleVal<T>(array: [T]) -> T? {
guard !array.isEmpty else { return nil }
return array.sorted()[(array.count - 1) / 2]
}
Sometimes, we require specific types only i.e type which confirm comparable protocol
func middleVal<T: Comparable>(array: [T]) -> T? {
guard !array.isEmpty else { return nil }
return array.sorted()[(array.count - 1) / 2]
}
Above method will only accepts. int, float, double.
If you have any comment, question, or recommendation, feel free to post them in the comment section below!