0

When I try to just set a constant based on the settings like below, it results in Optional("value").

let accesstoken = NSUserDefaults.standardUserDefaults().stringForKey("accessToken")
let userId = NSUserDefaults.standardUserDefaults().stringForKey("userId")

If I do it like the below, I get an error saying variable used within its own initial value. I can't seem to win here. What am I doing wrong?

var accesstoken = String()
var userId = Int()


if let atString = NSUserDefaults.standardUserDefaults().stringForKey("accessToken") {
    accesstoken = atString
}

if let userIdString = NSUserDefaults.standardUserDefaults().stringForKey("userId") {
    userId = userIdString
}

1 Answer 1

1

You can achieve what you want with a read only computed property combined with the nil coalescing operator "??". Try like this:

var accessToken: String {
    return NSUserDefaults().stringForKey("accessToken") ?? ""
}

var userId: String {
    return NSUserDefaults().stringForKey("userId") ?? ""
}

or if you need an Int for your userID

var userId: Int {
    return NSUserDefaults().integerForKey("userId")
}
Sign up to request clarification or add additional context in comments.

3 Comments

What does the ?? "" part at the end do?
it checks if the key has a value and if there is no value instead of returning nil you can define a default value for the key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.