Swift - Generic Type Extension

Introduction

Consider the following code:

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
         }
     }
}

When you extend a generic type, the parameter list in the original type definition is available in the extension.

Here, T is the placeholder name for the parameter type-you can write an extension for the MyStack class and it would also be available in the extension:

extension MyStack {
     func peek(position:Int) -> T! {
         if position<0 || position>elements.count-1 {
             return nil
         } else {
             return elements[position]
         }
     }
}

The preceding extension adds the peek() method to the MyStack class.

The following code shows how to use the new peek() extension method that you have just added:

Demo

class  MyStack<T>  {
     var elements =  [T ]()
     func push(item:T ) {
         elements.append(item)//w  w  w. j ava2  s.  c o m
     }

     func pop() -> T! {
         if elements.count>0 {
             return elements.removeLast ()
         } else {
             return nil
         }
     }
}
extension MyStack {
     func peek(position:Int) -> T! {
         if position<0 || position>elements.count-1 {
             return nil
         } else {
             return elements[position]
         }
     }
}

var myStack = MyStack<String>()

myStack.push(item:"The")
myStack.push(item:"Quick")
myStack.push(item:"Brown")
myStack.push(item:"Fox")

print(myStack.peek(position:0)) //The
print(myStack.peek(position:1)) //Quick
print(myStack.peek(position:2)) //Brown

print(myStack.pop())   //Fox
print(myStack.pop())   //Brown
print(myStack.pop())   //Quick
print(myStack.pop())   //The

Related Topic