-1

I want to add a member to a Node!
I thought that would work:

extension SKNode    {  
    var obstacleType:String =   ""  
}

But it didn't!
And I wanted to add the member like this:

ANode.obstacleType == "Stone" 

And cola it like this:

if ANode.name == "Obstacle" && ANode.obstacleType == "Stone" {  
    /* Do Something */  
}  

Is there a simple way to do it?

  • You cannot add properties in extensions. you can add computed properties only but these are get only (read only). I dont think there is another way to do it – Scriptable Jun 11 '18 at 13:19
  • https://stackoverflow.com/questions/48806204/why-extensions-cannot-add-stored-properties – Martin R Jun 11 '18 at 13:19
  • 2
    Possible duplicate of [Extension may not contain stored property but why is static allowed](https://stackoverflow.com/questions/45467329/extension-may-not-contain-stored-property-but-why-is-static-allowed) – Scriptable Jun 11 '18 at 13:25

1 Answers1

0

You can't have stored properties, only computed.

to get around this, just use userData:

extension SKNode    {  
    var obstacleType:String
    {
        get
        {
            return self.userData?["type"] ?? ""
        }
        set
        {
            self.userData = self.userData ?? [:]() //Guarentee it is created
            self.userData!["type"] = newValue
        }
    }  
}
Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44