Monday, February 2, 2015

Generic Functions in Swift.


Generic is one of the powerful feature of Swift. Most of the Swift Standard library uses this feature.

For instance, Swift Array and Dictionary are Generics Collection which can hold the value of any Type. You can create the array which holds Int values or String values.

With Generics code, developer can write flexible and reusable function which can work with any Type.

Suppose you have to write a function to swap two Int values. 



In Swift, parameters are passed by value so you can’t change the parameters value within the Function. If you want to modify the parameters value then you have to define the parameters as inout.

When you call a  function with an inout parameters, you use ampersand (&). This is something like passing the address of values as we have in C language.

If you want to write a function which can swap String or Doubles values then your function will look like this.





You may have noticed that all these functions bodies are same. Only difference is the type of the value passed to this functions.

So, you can write Generics functions which can work with any Type.




Generics function uses a placeholder type in angular bracket instead of actual Type name (Int, String). Both parameter a and b must be of same T type whatever T represents. 






No comments:

Post a Comment