Brennan Adler
Brennan Adler

Reputation: 915

NSUserDefaults properly storing Strings in SpriteKit Swift

So I set up a NSUserDefault to store a string in my GameViewController

 NSUserDefaults.standardUserDefaults().setObject("_1", forKey: "SkinSuffix")

The idea is it stores a suffix which I will attach to the end of an image name in order to save what skin of a character the player should use.

When I call the value in my GameScene class like so

var SkinSuffix = NSUserDefaults.standardUserDefaults().stringForKey("SkinSuffix")
println(SkinSuffix)

it prints "Optional("_1")" instead of just "_1" so when I try to change the name of my image file like so, it doesn't load the image file

hero = SKSpriteNode(texture: heroAtlas.textureNamed("10Xmini_wizard\(SkinSuffix)"))

How do I fix this issue?

Upvotes: 2

Views: 366

Answers (3)

Luca Angeletti
Luca Angeletti

Reputation: 59536

You can unwrap the String using the Optional Binding construct. This avoids a crash of the app if the value is nil.

if let skinSuffix = NSUserDefaults.standardUserDefaults().stringForKey("SkinSuffix") {
    println(skinSuffix)
}

Update: As correctly suggested in the comment below, I am putting the retrieved value in a constant (let). We should always use constants when we don't need to change the value. This way the Swift compiler can make some optimizations and does prevent us from changing that value.

Upvotes: 3

Leo Dabus
Leo Dabus

Reputation: 236538

You can use "??" Nil Coalescing Operator to help you dealing with nil and it also allows you to specify a default string value.

NSUserDefaults().setObject("_1", forKey: "SkinSuffix")

let skinSuffix = NSUserDefaults().stringForKey("SkinSuffix") ?? ""
println(skinSuffix) // "_1"

Upvotes: 0

Aaron
Aaron

Reputation: 6714

That's because it's implicitly an optional not of type String. You need to case it as such or unwrap the optional in your println statement.

var SkinSuffix = NSUserDefaults.standardUserDefaults().stringForKey("SkinSuffix") as! String

Or in your println: println(SkinSuffix!)

As a side note, you should you camelCase for your variable names.

Upvotes: 2

Related Questions