Last active
February 27, 2020 11:25
-
-
Save devjangir/902370f0e44470358c4b7f935ed8108f to your computer and use it in GitHub Desktop.
Generic Stack Implementation using protocol approach
This file contains hidden or 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
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