Ryan Ryan - 4 months ago 23
Swift Question

Unwrapping String from NSUserDefaults list

I am very new to swift and the unwrapping concept. I am trying to store an array of strings into NSUserDefaults. After printing the result to the console, the array shows up as

[Optional("VarOne"), Optional("VarTwo")] //the two test variables stored in the array


The goal is to achieve:

["VarOne", "VarTwo"]


I have done many tests to get a similar solution. My code is as follows:

let defaults = NSUserDefaults.standardUserDefaults()

if let array = defaults.arrayForKey("listOfPlayers"){

for i in array{
print(i)
}

}


My main question is how to unwrap the variables in this situation. To clarify, these are String variables.

EDIT: I included my code where I add the array to NSUserDefaults

let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(listOfPlayers, forKey: "listOfPlayers")
userDefaults.synchronize()

Answer

Try this:

   let defaults = NSUserDefaults.standardUserDefaults()

if let array = defaults.arrayForKey("listOfPlayers"){

    for i in array{
      let io = i as! AnyObject
    print(io)
    }

}
Comments