Using generics to write generic and reusable code
Generic code is used to write reusable and flexible functionalities that can deal with any type of variables. This helps in writing reusable and clean code regardless of the type of objects your generic code deals with. An example of using generics is 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 natively created and can deal with any type. Swift gives you the ability to write generic code very easily as you will see in this section.
Getting ready
Before learning how to write generic code, let's see an example of a problem that generics solve. I bet you are familiar with stack data structures and have been using it in one of the computer science courses before. Anyway, it's a kind of collection data structure that follows LIFO (Last in first out). It has very commonly used APIs for these operations, which are pop and push. Push inserts new item to the stack; pop returns the last inserted one. It's just a simple overview, as we will not explain data structures in this book as it's out of topic.
How to do it...
Here, we will create the stack data structure with/without generics:
Create a new playground named
Generics
.Let's create the data structure stack with type
Int
:class StackInt{ var elements = [Int]() func push(element:Int) { self.elements.append(element) } func pop() ->Int { return self.elements.removeLast() } func isEmpty()->Bool { returnself.elements.isEmpty } } var stack1 = StackInt() stack1.push(5) // [5] stack1.push(10) //[5,10] stack1.push(20) // [5,10,20] stack1.pop() // 20
Let's see the same created stack but with a generics fashion:
class Stack <T>{ var elements = [T]() func push(element:T) { self.elements.append(element) } func pop()->T{ return self.elements.removeLast() } } var stackOfStrings = Stack<String>() stackOfStrings.push("str1") stackOfStrings.push("str2") stackOfStrings.pop() var stackOfInt = Stack<Int>() stackOfInt.push(4) stackOfInt.push(7) stackOfInt.pop()
How it works...
The first class we created, StackInt
, is a stack that can work only with the Int
type. It's good if you are going to use it with Int
type only. However, a famous data structure like it can be used with different types, such as String
or Double
. It's not possible to create different stack class for each type, and here comes the magic of generics; instead we created another class called Stack
marked with <T>
to say it's going to deal with the generic type T
, which can be Int
, String
, Double
, and so on. Then, we create two stack instances, stackOfStrings
and stackOfInt
, and both share the same code as their class is built with generics.