HarveyBrCo
HarveyBrCo

Reputation: 825

Swift Spritekit setvalue

In swift with spritekit I want to set a variable of a sprite so I tried to say

p.setValue(value: (String(c)), forKey: "co")

But this gives an error.

So the main question is:

How can i set a key value pair in a sprite to a string as a key and an int/string as a value?

Upvotes: 0

Views: 373

Answers (2)

rickster
rickster

Reputation: 126107

setValue(_:forKey:) and related methods aren't for associating arbitrary key/value data with an object. They're part of Key-Value Coding, a Cocoa feature that does all sorts of handy things — but unless a class does something special with KVC, all setValue(_:forKey:) does is let you set one of that class's declared properties using a string instead of by directly accessing a property. In other words, the two lines below are equivalent:

node.name = "foo"
node.setValue("foo", forKey: "name")

If you want to associate arbitrary key-value pairs with your sprites—which can be a great way to keep track of entities in your game—use the userData property.

Upvotes: 2

Nate Cook
Nate Cook

Reputation: 93276

To use setValue:forKey: you need to have (a) a valid key, and (b) a value of the correct type for that key. For example:

mySprite.setValue(UIColor.redColor(), forKey: "co")  // error, "co" isn't a valid key
mySprite.setValue("red", forKey: "color")            // error, "color" needs a UIColor value
mySprite.setValue(UIColor.redColor(), forKey: "color")   // works!

What value and key are you actually using?

Upvotes: 1

Related Questions