duglus
answered Apr 25 '23 00:00
To store an array in UserDefaults in Swift, you can use the set (_:forKey:) method, passing in the array and a unique key as parameters. For example:
let myArray = ["apple", "banana", "orange"]
UserDefaults.standard.set(myArray, forKey: "myArrayKey")
Here, we've created an array called myArray and saved it to UserDefaults with the key " myArrayKey ".
To retrieve the array later, use the array(forKey:) method. This method returns an optional array of Any objects, so you'll need to cast it to the appropriate type, like so:
if
let retrievedArray = UserDefaults.standard.array(forKey: "myArrayKey") as? [String] {
// Use the retrieved array
}
Here, we're using optional binding to unwrap the retrieved array, and casting it to an array of strings using the as ? operator. If the retrieved object is not an array of strings, the code inside the if block won't execute. If the object is an array of strings, we can use it as needed.