Book Image

Application Development with Swift

By : Hossam Ghareeb
Book Image

Application Development with Swift

By: Hossam Ghareeb

Overview of this book

Table of Contents (14 chapters)

Generics


The generic code is used to write usable and flexible functionalities that can deal with any type. This helps you avoid duplication and write code that is very clean and easy to edit and debug. Examples of using generics are when you use Array and Dictionary. You can create an array of Int or String or any type you want. That's because Array is generic and can deal with any type. Swift gives you the ability to write generic code very easily, as you will see in the following example. In the example, we will explain how to use Stack data structure. Stack is commonly used in algorithms and data structures. You can notice the use of stack in UINavigationController, as the view controllers are inserted in a stack, and you can easily push or pop view controllers.

Before implementing stack in a generic way, we will build it first for the Int type only, and then we will build it generically to see the difference. Check the following code:

class StackInt{
    var elements = [Int]()
    
 ...