Skip to content

Instantly share code, notes, and snippets.

@kevinvanderlugt
Last active August 29, 2015 14:02
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 kevinvanderlugt/5a42fc3188e4ea22209b to your computer and use it in GitHub Desktop.
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
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