2

I want to set a value for an SKSpriteNode. So, I made an extension to SKSpriteNode called HAKEK

I've tried this

var HAKEK: Int {
        get {
            return self.HAKEK

        }
        set {
            self.HAKEK = newValue

        }
    }

But it doesn't work cause it keep returning it self, so how do I let It get its own value which is set in the setter?

Saveen
  • 4,120
  • 14
  • 38
  • 41
Harcker
  • 23
  • 1
  • 3
  • Read https://stackoverflow.com/questions/24025340/property-getters-and-setters, it will help understanding. – Ankit Jayaswal Apr 04 '18 at 19:17
  • What do you _really_ want to achieve? – Luca Angeletti Apr 04 '18 at 19:21
  • You *cannot* add a stored property in an extension: https://stackoverflow.com/questions/29025785/swift-why-cannot-add-store-property-in-extension-whats-the-different-between. See https://stackoverflow.com/questions/25426780/how-to-have-stored-properties-in-swift-the-same-way-i-had-on-objective-c for some kind of workaround. – Martin R Apr 04 '18 at 19:26
  • I want to set a value for some SKSpriteNodes, a value could be lives – Harcker Apr 04 '18 at 19:36

1 Answers1

2

You can't create stored properties in extensions as others have mentioned. Normally I would agree with others in using associated objects, but with SKNode, there is an even better property to work with. It is called userData, and it is designed to allow your nodes to hold custom data.

extension SKSpriteNode
{
    var HAKEK: Int {
        get {
            return self.userData?["HAKEK"] ?? 0

        }
        set {
            self.userData = self.userData ?? [String:AnyObject]()
            self.userData["HAKEK"] = newValue

        }
    }
}

Of course, I would not extend SKSpriteNode if this property is not going to be available to all SKSpriteNodes. If this is a unique case, you may want to sub class, which means this extension isn't even needed.

Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44