Wednesday 29 August 2018

Generics in iOS Swift

The main use of Generic is avoid code duplication.
Generic placeholder is defined within angle brackets <>.

For example there are two array with different type.

let arrayOfInt = [5,10,15,20]
let arrayOfString = ["Karan","Ankur","Bunty"]

For print this array of value you can create two function like

func printInt(fromArrayOfInt arrayOfInt:[Int]){
    arrayOfInt.map({print($0)})

}

func printString(fromArrayOfString arrayOfString:[String]){
    arrayOfString.map({print($0)})
}

And use

printInt(fromArrayOfInt: arrayOfInt)
printString(fromArrayOfString: arrayOfString)

Output:

5
10
15
20
Karan
Ankur
Bunty

Now using Generic no need to create two function. We can print all type of array using single function like 


func printArray<T>(fromArray arrayOfValue: [T]){
    arrayOfValue.map({print($0)})
}

and calling is same

printArray(fromArray: arrayOfInt)
printArray(fromArray: arrayOfString)

In order to use Generic with struct, class or enum, you can define the Generic placeholder after the name. 

Github link : Generics

You can also watch video : 



No comments:

Post a Comment