I made this implementation of a stack in Swift that stores its elements as a linked list. It seems to work perfectly well, but I’m wondering how I can improve it to follow the best practices of the language.
struct StackList<T> : CustomStringConvertible {
private var first: StackNode? = nil // The topmost node in the stack
/// Add a new element to the top of the stack
/// - parameter newElement: the new element to be added
mutating func push(_ newElement: T) {
let newElement = StackNode(newElement);
newElement.next = first;
first = newElement;
}
/// Remove and return the topmost element from the stack
/// - returns: Optional containing the removed element, or nil if the stack was empty
mutating func pop() -> T? {
guard let first = first else { return nil }
let poppedElement = first.element
self.first = first.next
return poppedElement
}
/// The number of elements in the stack
var size: Int {
var count = 0
var current = first
// Traverse the list
while current != nil {
count += 1
current = current!.next
}
return count
}
/// Textual representation of the stack
var description: String {
var output = ""
// Traverse the list
var currentNode = first;
while let thisNode = currentNode {
if output != "" { output += ", " } // Add commas between elements
output += String(describing: thisNode.element)
currentNode = thisNode.next
}
return "[\(output)]"
}
private class StackNode {
var next: StackNode? = nil
var element: T
init(_ element: T) {
self.element = element
}
}
}