I'm pretty excited about this new feature in Swift; Generics. This is something borrowed from C++. The `Swift Programming Language` book stated "Generic Code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements you define". Basically it just means you can write functions that can work with multiple types of parameters, collection types that can perform operations on the data set without any concerns of the type of the data set.
In the above snippet, you can see, <T> is the additions, right next to class name, that makes it a generic type. You can make use Type T within the implementation just like any other type.
You can check the sample project here in Github.
Below is a Gist of Generic Stack Implementation in Swift, a Stack that can work with any data types.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Stack<T> { | |
var items = T[]() | |
//Push method | |
func push(item: T) | |
{ | |
items.append(item) | |
} | |
//Pop method. | |
//If the array is not empty, then the last element pushed will be returned else nil. | |
func pop() -> T? | |
{ | |
var returnItem :T? | |
//If array is not empty | |
if items.count != 0 | |
{ | |
returnItem = items.removeLast() | |
} | |
return returnItem | |
} | |
//Prints out all the elements to the console | |
func traverse() | |
{ | |
println("---- Stack ----\n") | |
for item in items.reverse() | |
{ | |
println(item) | |
} | |
println("\n") | |
} | |
} |
In the above snippet, you can see, <T> is the additions, right next to class name, that makes it a generic type. You can make use Type T within the implementation just like any other type.
You can check the sample project here in Github.