Reputation: 2298
I have a class called Node. When I initialize Node, I want its previous node and next node to always point to itself- makes a circulating-endless string of nodes.
class Node {
var name: String!
var previousNode: Node = self // error
var nextNode: Node = self // error
init?(name: String) {
if name.isEmpty {
return nil
}
self.name = name
}
func setPreviousNode(prevNode: Node) {
self.previousNode = prevNode
}
func setNextNode(nextNode: Node) {
self.nextNode = nextNode
}
}
How can I automatically assign a variable to self in class?
Upvotes: 2
Views: 2129
Reputation: 40955
Since you cannot refer to self
until all of self’s properties are initialized, you have to take a two-phase approach and use init
– but you also need to make the nodes optional, since you’ll need to set them to something first (e.g. nil
) and then set them to self again after all self’s properties (including them) have been set.
You could take the same approach as you’re using with name
and make them implicitly optional for convenience later, so long as you’re careful to ensure they’ll never be nil
.
class Node {
var name: String!
var previousNode: Node!
var nextNode: Node!
init?(name: String) {
if name.isEmpty {
return nil
}
self.name = name
previousNode = self
previousNode = self
}
// since this takes a `Node` not a `Node?` you know
// it can’t set them to nil, which is good
func setPreviousNode(prevNode: Node) {
self.previousNode = prevNode
}
func setNextNode(nextNode: Node) {
self.nextNode = nextNode
}
}
let node = Node(name: "fred")
// good to know the playground printing code checks for cycles!
// {name "fred" {name "fred" {…} nil} nil}
Upvotes: 1