Last active
August 10, 2017 08:59
-
-
Save hemangshah/74c9eb0317f71a50fe66f1fe1dfeda80 to your computer and use it in GitHub Desktop.
This is the demonstration of Stack in Swift. I have used the default functions to handle the Stack operations.
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
//: Playground - noun: a place where people can play | |
import Foundation | |
class Stack { | |
static let list = Stack.init() | |
private var items = Array<Any>() | |
internal var limit = 5 | |
//MARK: Push | |
internal func push(item: Any) -> Void { | |
if isReachesToMaxLimit() { | |
print("Stack reaches to the maximum limit \(limit). Couldn't insert >>>\(item)<<<") | |
return | |
} | |
items.append(item) | |
} | |
//MARK: Pop | |
internal func pop() -> Any? { | |
guard !isEmptyList(showMessage: true) else { | |
return nil | |
} | |
return items.removeLast() | |
} | |
internal func pop(completion: (Any)->()) { | |
if !isEmptyList(showMessage: true) { | |
completion(items.removeLast()) | |
} | |
} | |
//MARK: Get Items | |
internal func getItems() -> Array<Any>? { | |
if isEmptyList(showMessage: true) { | |
return nil | |
} | |
print("------------------------------------------------------------------------------------------------------------------") | |
print("Items in Stack") | |
print("------------------------------------------------------------------------------------------------------------------") | |
items.forEach { (item) in | |
print(item) | |
} | |
return items | |
} | |
//MARK: Validators | |
private func isEmptyList(showMessage: Bool) -> Bool { | |
if items.isEmpty { | |
if showMessage { | |
print("Stack is empty.") | |
} | |
return true | |
} | |
return false | |
} | |
private func isReachesToMaxLimit() -> Bool { | |
if !isEmptyList(showMessage: false) { | |
if items.count >= limit { | |
return true | |
} | |
} | |
return false | |
} | |
// //MARK: Search Item | |
// internal func search(item searchItem: Any) -> Bool { | |
// if isEmptyList(showMessage: true) { | |
// return false | |
// } | |
// | |
// items.contains { (item) -> Bool in | |
// if searchItem == item { | |
// return true | |
// } | |
// } | |
// | |
// return false | |
// } | |
} | |
//Usage - Push | |
Stack.list.push(item: "A") | |
Stack.list.push(item: "B") | |
Stack.list.push(item: "C") | |
Stack.list.push(item: "D") | |
Stack.list.push(item: "E") | |
//Usage - List Items | |
Stack.list.getItems() | |
Stack.list.push(item: "F") | |
Stack.list.pop { (item) in | |
print(">>>\(item)<<< is popped.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment