DEV Community

Cover image for Exploring Deque in Swift Collections
Rizwan Ahmed
Rizwan Ahmed

Posted on • Originally published at ohmyswift.com

Exploring Deque in Swift Collections

Deque (should be pronounced as "deck") is a collection implementing double-ended queues. Deques are similar to arrays, but they have efficient insertions and removal of elements at the beginning and at the end.

The indexing semantics are integer indices that are the same as arrays.
Now let's see a sample implementation of deque.

var colors: Deque = ["Yellow", "Orange"]
print(colors) // [Yellow, Orange]
Enter fullscreen mode Exit fullscreen mode

The above code implements a deque of colors with the strings yellow and orange.

Deque operations

Now let's see some operations or methods unique to deques.

1. prepend - Adding an element at the beginning of the deque.

colors.prepend("Blue") // Blue is added to the beginning
Enter fullscreen mode Exit fullscreen mode

2. append - Adding an element to the end of the deque.

colors.append("White") // White is added to the end
Enter fullscreen mode Exit fullscreen mode

3. popFirst - Removal of an element from the beginning of the deque.

let _ = colors.popFirst() // Blue is removed
Enter fullscreen mode Exit fullscreen mode

4. popLast - Removal of an element from the beginning of the deque.

let _ = colors.popLast() // White is removed
print(colors) // [Yellow, Orange]
Enter fullscreen mode Exit fullscreen mode

This article was originally published at ohmyswift.com. Click here to read the full article.

About the author πŸ‘¨β€πŸ’»

Rizwan Ahmed β€” iOS Engineer.
Twitter πŸ‘‰ https://twitter.com/rizwanasifahmed
Like our articles? Support us πŸ‘‰https://www.buymeacoffee.com/ohmyswift

Top comments (0)