In Swift, a stack can be implemented using an array and the following methods:
push(_ item: T) -- adds an element to the top of the stack
pop() -> T? -- removes and returns the element at the top of the stack
peek: T? —
isEmpty: Bool -- returns a boolean indicating if the stack is empty
Here is an example to illustrate that. First, we define two classes, WebPage and WebBrowser, which simulate a basic web browsing functionality.
After that, we call the navigateBack method three times to simulate navigating back to previously visited pages. The output of each navigation is printed.
Finally, we call navigateBack one more time to simulate navigating back when the browser is empty. It prints a message indicating that the browser is empty.