Exploring Deque in Swift Collections

Deque (should be pronounced as “deck”) is a collection implementing double-ended queues.

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]

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

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

colors.append("White") // White is added to the end

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

let _ = colors.popFirst() // Blue is removed

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

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

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

About the author 👨‍💻

Like our articles? Support us 👇 https://www.buymeacoffee.com/ohmyswift

iOS Engineer @zoho , Creator — http://ohmyswift.com Support OhMySwift by buying us a pizza! 👉 https://buymeacoffee.com/ohmyswift