Swift - Custom Type Generic Classes

Introduction

Consider the following example:

class  MyStack<T>  {
    var elements =  [T ]()
    func push(item:T ) {
        elements.append(item)
    }

    func pop() ->  T! {
        if elements.count>0 {
            return elements.removeLast ()
        } else {
            return nil
        }
    }
}

To use the MyStack class for Int values, specify the data type enclosed with angle brackets <> during instantiation of the class:

var myIntStack = MyStack<Int> ()

You can now use the class as usual:

myIntStack.push(item:5)
myIntStack.push(item:6)
myIntStack.push(item:7)
print(myIntStack.pop())     //7
print(myIntStack.pop())     //6
print(myIntStack.pop())     //5
print(myIntStack.pop())     //nil

You can also use the MyStack class with the String type:

var myStringStack = MyStack<String> ()
myStringStack.push(item:"Programming")
myStringStack.push(item:"Swift")
print(myStringStack.pop())  //Swift
print(myStringStack.pop())  //Programming
print(myStringStack.pop())  //nil

Demo

class  MyStack<T>  {
    var elements =  [T ]()
    func push(item:T ) {
        elements.append(item)//from   w  w  w  . j  a v  a2s  .c om
    }

    func pop() ->  T! {
        if elements.count>0 {
            return elements.removeLast ()
        } else {
            return nil
        }
    }
}

var myIntStack = MyStack<Int> ()

myIntStack.push(item:5)
myIntStack.push(item:6)
myIntStack.push(item:7)
print(myIntStack.pop())     //7
print(myIntStack.pop())     //6
print(myIntStack.pop())     //5
print(myIntStack.pop())     //nil

var myStringStack = MyStack<String> ()
myStringStack.push(item:"Programming")
myStringStack.push(item:"Swift")
print(myStringStack.pop())  //Swift
print(myStringStack.pop())  //Programming
print(myStringStack.pop())  //nil

Related Topic