devios devios - 7 months ago 18
Swift Question

Reference `self` in Swift instance member declaration

I have a

struct
set up that accepts a reference as a single initialization parameter:

internal struct NodeState: Equatable {
weak var node: Node! = nil
// ...

init(node: Node) {
self.node = node
}
}


I want to instantiate a
NodeState
as a member of the
Node
class, passing
self
in to set that weak reference:

public class Node: NSObject {
internal var state = NodeState(node: self)
// ...
}


…but I am getting this weird compile error:


Cannot convert value of type 'NSObject -> () -> Node' to expected argument type 'Node'


Am I not allowed to reference
self
in a member declaration in Swift?

Answer

In general you can't reference self in a member class declaration but you can if you make the property lazy and initialize it with a closure. Changing your Node class to something like this should work:

public class Node: NSObject {
    internal lazy var staticState: NodeState = { NodeState(node: self) }()
}

It works because the lazy property isn't initialized until after self is initialized. self has to be fully initialized before it can be used.