devios devios - 5 months ago 7x
Swift Question

Reference `self` in Swift instance member declaration

I have a

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
as a member of the
class, passing
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
in a member declaration in Swift?


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.