-1

Hey guys so I know that we can append single string to userdefault but I was wondering how we can append [String: String]

So here is my code

 var savedArray = UserDefaults.standard.array(forKey: "array1") as! [String]

   let name = John
   let lastname = Smith
   if let index = savedArray?.index(where: {$0 != name!}) {
    savedArray?.append(name!)
   }
   //this code works fine but now I want to add more than just name. So I tried this code below

   if let index = savedArray?.index(where: {$0 != name!}) {
    savedArray?.append(name!, lastname!)
   }

But then I get a error that says extra argument in call. So I am assuming that because on top I put as! [String]. But if I put

   var savedArray = UserDefaults.standard.array(forKey: "array1") as! [String: String]

I can't append this variable because the error message says that append is not available for String: String. Is there anyway to append multiple strings into a Userdefault? When I tried to google this it only shows how to set your userdefaults to the strings but I want to keep adding values into the userdefaults.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Dkeem
  • 9
  • 5

2 Answers2

1

Just append twice:

savedArray?.append(name!)
savedArray?.append(lastname!)

Or you can use append(contentsOf:) with an array, but there seems no need for that here.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • k so savedArray?.append(name!) was working fine yesterday. Now its just printing nil everytime... – Dkeem Feb 27 '18 at 06:00
1

You are using too many question and exclamation marks. Since savedArray, name and lastName are non-optional you will get a couple of compiler errors with the optional syntax anyway.

Rather than googling the stuff I recommend to read the documentation, there are examples how to append multiple elements. And contains is preferable over index in this case:

if !savedArray.contains(name) {
    savedArray.append(contentsOf: [name, lastname])
}
vadian
  • 274,689
  • 30
  • 353
  • 361