Skip to content

Instantly share code, notes, and snippets.

@devjangir
Last active February 27, 2020 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devjangir/902370f0e44470358c4b7f935ed8108f to your computer and use it in GitHub Desktop.
Save devjangir/902370f0e44470358c4b7f935ed8108f to your computer and use it in GitHub Desktop.
Generic Stack Implementation using protocol approach
import CoreFoundation
//Generic Type Protocol
public protocol Stackable {
//Generic Type
associatedtype E
// Push - add new element to stack array
mutating func push(_ element: E)
// Pop - remove and return last element of array
mutating func pop() -> E?
// Peek - return last element of array
func peek() -> E?
//count the number of element in stack
var count : Int { get }
//check for empty stack list
var isEmpty: Bool { get }
}
//Stack Implementation
public struct Stack<T> : Stackable {
var items = [T]()
//init with array items
init(_ elements : [T]) {
items = elements
}
// Push - add new element to stack array
mutating public func push(_ element: T) {
items.append(element)
}
// Pop - remove and return last element of array
mutating public func pop() -> T? {
items.popLast()
}
// Peek - return last element of array
public func peek() -> T? {
items.last
}
//count the number of element in stack
public var count : Int {
items.count
}
//check for empty stack list
public var isEmpty: Bool { items.isEmpty }
}
//create stack using array literal
extension Stack : ExpressibleByArrayLiteral {
public init(arrayLiteral elements: T...) {
items = elements
}
}
//customize stack description by implement CustomStringConvertible protocol
extension Stack : CustomStringConvertible {
public var description: String {
return items.map {"\($0)" }.joined(separator: " ")
}
}
//create stack (string type) object using standard init method
var stringStackWithInit = Stack<String>()
stringStackWithInit.push("swift")
stringStackWithInit.push("5")
//create stack (string type) object using init with array
var stringStackWithInitArray = Stack<String>(["swift","5"])
//create stack (string type) object expressible by array literal
var stringStackArray : Stack = ["swift","5"]
print(stringStackWithInit.description)
print(stringStackWithInitArray.description)
print(stringStackArray.description)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment