WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Is there a Stack implementation in swift5

Forums > Swift

Im learning algorithms at university and wanted to implement Graham's scan algorithm, it uses a stack for storring the results on its way through the data. It seems that swift don't have an implementation of the Stack datastructure, with the tree functions Peek(),Pop(),Add() is that correct?


A stack is really nothing more than an array with limited access methods. So while there's no built-in stack structure in the standard library, it's very easy to roll your own using Array and its methods.


@twostraws created a very nice video about the Swift open source project on sequence and collection algorithms. These are a number of power library add-ons addressing unique sequences, chunking, compacting trees, and more.

See > Write better code with Swift Algorithms

In addtion to algorithms, Apple's open source github has a Swift Collections library. With more advanced goodies.

I didn't do a deep dive into the ReadMe files, but this library has Deque, Heap and other structures. Deque does have popLast() and popFirst() methods out-of-the-box.

Take a look there! Or as @rooster notes, code your own!

See > Github Swift Collections

Please report back! We want to know if you found a great library to use!


There is quite a detailled answer here.

Or, even better, a full session on the topic with example code, by Paul Hudson.


Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.