Tags
swift
Asked 4 years ago
13 Jan 2020
Views 926
iptracker

iptracker posted

how to store array by UserDefaults.standard.set

i have following array

 var myLoactionlist = [Int:  [String: String]]()
 var itemcount : Int = 0

for loc in location  {
                                                myLoactionlist[itemcount] = ["latitude" : loc["latitude"] , "longtitude" : loc["longtitude"] ]

}



how to store array in UserDefaults.
duglus

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.
Post Answer