From the course: Swift 5: Protocol-Oriented Programming
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Solution: Implementing a generic stack
From the course: Swift 5: Protocol-Oriented Programming
Solution: Implementing a generic stack
(upbeat music) - [Narrator] So, how did it go? Hopefully, you managed to implement your array-based stack. You can follow along with me and check out my solution. First, I import the foundation framework. We'll need it for the various built-in data types. Now, let's define the protocol. It is public, and I call it stack protocol. Our stack needs to work with any type. Therefore, I introduce a placeholder type for the elements, using the associated type keyword, and I call the placeholder E, for elements. Next, I'm going to define the method requirements. First, the push method. Since pushing new elements into the stack's internal storage will modify the instance, I mark the method as mutating. The method takes a single argument, I'm going to call it item, of type E. The pop method returns, and removes, the top element from the stack. This method should also be declared as mutating, since it removes an element from the…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.