Last active
August 29, 2015 14:02
-
-
Save kevinvanderlugt/5a42fc3188e4ea22209b to your computer and use it in GitHub Desktop.
Playing around with Swift to implement a Queue that can take any object type
This file contains 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
class Queue { | |
var items: Array<AnyObject> = [] | |
// Add an object to the tail of the queue | |
func enqueue(object: AnyObject) { | |
items += object; | |
} | |
// Remove the head of the queue and return the object | |
func dequeue() -> AnyObject? { | |
assert(items.count > 0, "Array has no items to dequeue") | |
let object : AnyObject? = items[0] | |
items.removeAtIndex(0) | |
return object | |
} | |
// Empty the entire queue | |
func clear() { | |
items.removeAll(keepCapacity: false) | |
} | |
// Return if the queue is empty | |
func empty() -> Bool { | |
return items.count == 0 | |
} | |
// Implement the subscript to peek at any index using queue[1] notation | |
subscript(index: Int) -> AnyObject? { | |
assert(index < items.count, "Index is out of bounds") | |
return items[index]; | |
} | |
// Return the object at the index a wrapper for using subscript notation | |
func peek(index: Int) -> AnyObject { | |
return items[index] | |
} | |
// Return the object at the front of the queue without mutation | |
func peekHead() -> AnyObject { | |
return items[0] | |
} | |
// Return the object at the end of the queue without mutation | |
func peekTail() -> AnyObject { | |
let index = items.endIndex - 1 | |
return items[index] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment