Swift Generics

Swift Generics

Generics in swift has very great importance. you will see its useful ness .you can avoid redundant code and implement a fancy yet powerful programs.Generics as word implies it means the things in general, which are not specified explicitly.

Lets take an example , instead of boring theory and make things little interesting 🙂
Many of you must have implemented or studied data structures – Stacks , Queues .
so we will write a simple code where we will push Integers to the stack.
and best way to learn from here is to start typing this code yourself in playground.

struct IntStack {
var items = [Int]()

func push(item:Int) {
items.append(item)
}

func pop() -> Int {
return items.removeLast()
}

}

Well Now whats that there is a error “warning: immutable value ‘value’ was never used”.
So as you can see we have declared struct , and there is struct feature if you want to modify declared vars(items[]) , you need to make that function mutable , and there is a keyword “mutating” for it. So now lets modify our code by adding mutating before our func.

struct IntStack {
var items = [Int]()

mutating func push(item:Int) {
items.append(item)
}

mutating func pop() -> Int {
return items.removeLast()
}
}

Now It will work and you try pushing,poping elements as:

var stack = IntStack(items: [2,3,4])
stack.push(item: 8)
print(stack.items)
stack.pop()
print(stack.items)

Now this Stack will only push Integers. Now if you want to push some other data type , you will write a another stack for lets say Strings.In which you will declare array of string type.

But that is where you are writing redundant code, so generics will help you write a code in such a way that you can make your stack generic.

To declare generic struct , you need to add <Element> this angular bracket.
and declare your array items as var items = [SomeDataType]().

That’s it. and have made your generic type stack:

struct Stack<Element> {
var items = [Element]()

mutating func push(item:Element) {
items.append(item)
}

mutating func pop() -> Element {
return items.removeLast()
}
}

and try pushing , poping string with it .
var gSTack = Stack(items: [“abc”])
gSTack.push(item: “klk”)
print(gSTack.items)
gSTack.pop()

and you can use same stack for Int,Double etc.

I Hope You will now make use of generics in a beautiful way .