generic function example code swift

By | August 16, 2016

generic function example code swift

Generic means that “something that is general”. In programming, generic data type means that when we make a generic type that means we can use it as any other data type like Int, Float or String.

For example, we need to swap to values. So, we will write a function for swapping two values. When we write a normal function then either we can pass two Int parameters and swap them but if we try to pass two Float or String then will lead into error. So, we will create two more functions to deal with this having Float and String parameters.

In swift, we can write generic function. That means no matter which two data type values we need to exchange we can write one common function for that. This function is called generic function.

In following example, we have used the same function “swapValues” to exchange two Int values of a and b as well as two String values of name and anothername.

Note: Here, we can only exchange the same datatype values and pass it to the function parameters. Two Int or Two Float can be exchanged. But an Int value can not be exchanged with a Float. Swift has its own “swap” function for this purpose in swift standard library.