From the course: Swift 5: Protocol-Oriented Programming

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Challenge: Implementing a generic stack

Challenge: Implementing a generic stack

From the course: Swift 5: Protocol-Oriented Programming

Start my 1-month free trial

Challenge: Implementing a generic stack

(electronic music) - [Instructor] The stack is a sequential container that provides a last-in, first-out access. We can push new items onto the top of the stack. Accessing the most recently added element is possible using peek, or pop. Your task is to implement a generic stack that exposes the following methods and properties. Push, adds the element to the top of the stack. Pop, returns and removes the top element from the stack. The method should return nil if the stack is empty. Peek, returns the top element or nil if the stack is empty. Count, returns the number of elements in the stack, and isEmpty returns a Boolean value indicating whether the stack has no elements. Now, some hints. You should start by defining the protocol. The count and isEmpty properties should be read only. The methods that modify the instance should be declared as mutating. Then, create the stack type that adopts the protocol. You can use an…

Contents