##tl;dr I wrote a stack using linked list in Swift
When I try to learn a new language, I try writing a stack using a linked list. This makes you learn a few basic things about the language and helps you become familiar with the language faster. I decided to do the same with Swift.
As a prerequisite, you need XCode 6 Beta in order to run Swift.
1. Define classes
I created two classes in different files in XCode.
2. Define attributes of the Node class
I defined two attributes called:
value is an optional attribute with
value is optional because it may have
value is typed as
NSObject because we want
the Node to handle multiple types of value such as
integer, double and string.
next is also on optional attribute because some nodes may
not have any next node. So
next might be
is typed as
Node because it points to another node.
init functions in Node
We want two
init functions because we want to
instantiate a node with some
value or without anything.
We are done with Node class
init function for Stack and its attributes
head points to the top of the stack.
count has the total number of nodes in the stack.
isEmpty function returns
true if the stack is empty
false if the stack is not empty.
push function inserts some value to the top of the stack.
pop function removes some value from the top
of the stack.
This function has optional return type because if the
stack is empty, it should return nothing,
In the line,
self.head = node.next!, we use
! to force
the optional variable to unwrap its value.
You can see the full source code on github.