Generics in iOS swift

Abhimuralidharan
3 min readMay 18, 2017

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.

Generics are one of the most powerful features of Swift, and much of the Swift standard library is built with generic code. In fact, you’ve been using generics throughout the Language Guide, even if you didn’t realize it. For example, Swift’s Array and Dictionary types are both generic collections. You can create an array that holds Int values, or an array that holds String values, or indeed an array for any other type that can be created in Swift. Similarly, you can create a dictionary to store values of any specified type, and there are no limitations on what that type can be.

Lets understand generics with the help of good code and bad code.

Example:

Consider two arrays:

let intArray = [1,2,3,4,5] // type intlet stringArray = [“abhi”, “iOS”] // type string

We need to print all values in these two arrays. Let’s create a function to print int array, and another function to print all string values in string array.

func printIntArray(arr:[Int]) {arr.map { print($0) } // loop through the array and print all values

--

--