Reputation: 536
Making default index = 0
let defaults = NSUserDefaults.standardUserDefaults()
if !(defaults.objectForKey("LastIndex") != nil)
{
defaults.setObject(Int(0), forKey: "LastIndex")
}
Then trying to compare this index with random number
var randomIndex: Int = 0
let defaults = NSUserDefaults.standardUserDefaults()
let lastIndex: Int = Int(defaults.objectForKey("LastIndex"))
while randomIndex != lastIndex
{
randomIndex = Int(arc4random_uniform(UInt32(phrasesArray.count)))
}
but getting an error
Upvotes: 0
Views: 51
Reputation: 71854
If you want to store Int
int NSUserDefaults
you can do it directly this way:
NSUserDefaults.standardUserDefaults().setInteger(YourIntValue, forKey: "LastIndex")
Let me correct some of your code. First of all look at this code:
let defaults = NSUserDefaults.standardUserDefaults()
if !(defaults.objectForKey("LastIndex") != nil)
{
defaults.setObject(Int(0), forKey: "LastIndex")
}
You are checking here that if there is value available for LastIndex
or not but instead of trying that you can directly create a Int value with can directly read as Int
from your memory with this code:
let abc = NSUserDefaults.standardUserDefaults().integerForKey("LastIndex")
println(abc)
With this code if there is no value for key LastIndex
then it will set to 0
by default so it will print always 0
if there is nothing so you don't need to check if it is nil
or not.
Now look at this code:
let lastIndex: Int = Int(defaults.objectForKey("LastIndex"))
Here you are reading values from that key where you are trying to casting it as Int
but If you do it as I suggested you can directly get Int
value form it so just make it simple like:
let lastIndex = NSUserDefaults.standardUserDefaults().integerForKey("LastIndex")
This will always return Int and if there is nothing set then it will be 0
by default.
And you can perform your action as you want:
while randomIndex != lastIndex {
randomIndex = Int(arc4random_uniform(UInt32(phrasesArray.count)))
}
Hope it will help you.
Upvotes: 0
Reputation: 536
I found the solution – so simple that i even LOL'ed.
let lastIndex: Int = defaults.integerForKey("LastIndex")
Upvotes: 1