I'm trying to make a feature that saves a title and link to a website
This is what I am attempting to store
[0] -> [TITLE, LINK]
[1] -> [TITLE, LINK]
[2] -> [TITLE, LINK]
This is how I am doing it
//Create array
var favoriteProducts = [[String:String]]()
//Add products
let firstArray = [titleName:String(), link:String()]
favoriteProducts.append(firstArray)
//Add to defaults
UserDefaults.standard.set(favoriteProducts, forKey: "favProducts")
The next step is to loop through using ForEach
to return the title and link. For debugging I'm trying to use
UserDefaults.standard.array(forKey: "favProducts")![0][0]
Which returns
Value of type 'Any' has no subscripts
However
UserDefaults.standard.array(forKey: "favProducts")![0]
Returns
(website, link)
So my question here is how do I return both the website and link individually and not just the entire subscript?
CodePudding user response:
you can store arrayOfStrings In struct array and can access the vale from struct ,Say example
var favouriteProducts = [[String:Any]]()
var listOfSite = [SiteDetail]()
var firstArray = ["titleName":"String","link":"firstlink"]
var secondArray = ["titleName":"s","link":"s"]
favouriteProducts.append(firstArray)
favouriteProducts.append(secondArray)
UserDefaults.standard.set(favouriteProducts, forKey: "favProducts")
let value = UserDefaults.standard.array(forKey: "favProducts") as? [[String:String]] ?? [[:]]
for values in value{
let siteName = values["titleName"] as? String ?? ""
let link = values["link"] as? String ?? ""
let siteDetail = SiteDetail(website: siteName, link: link)
listOfSite.append(siteDetail)
}
print("listOf \(listOfSite[0].link)")
print("listOf \(listOfSite[0].website)")
//////////////////////////
struct SiteDetail{
var website:String?
var link:String?
}
CodePudding user response:
Here UserDefaults.standard.array
returns an array of Any
type and you are storing an array of the dictionary. So at the time of retrieve, you need to cast the array element as a dictionary.
Also, you can use the key to get the dictionary value.
let firstElement = (UserDefaults.standard.array(forKey: "favProducts")?[0] as? [String: String])
let title = firstElement?["titleName"]
let link = firstElement?["link"]