Working with Generics

Generics are one of the most powerful features of Swift.

For example Array and Dictionary types are both generic collections.

  • For arrays it can hold any data types eg. Int, String.
  • Similarly with Dictionary we can store values of any specified data type.

Generic Functions

A generic function uses placeholder type name called T. T placeholder is used on generic functions and on the type parameters as such.

func swapStuffs<T>(_ a: inout T, _ b: inout T {
  let tempA = a
   a = b
   b = tempA

We can provide more than one type parameters separate by comma within the angle brackets.

Naming Type Parameters

You can give type parameters descriptive name such as Dictionary<Key, Value> or Array<Element>. Always give type parameters upper case names.

Leave a Reply

Your email address will not be published. Required fields are marked *