0

I am developing an app that has a textView in FirstViewController and a tableView in the SecondViewController. In the app user types in a string using a textView, which is then turned into an array with the press of a button (indicated by an IBAction buttonIsPressed) and transferred onto a tableView in the next view controller with the help of UserDefaults. Right now, I want the code to be able to append all of the strings into one array every time user types in a string in textView. I have tried every single method I found on the internet to append either strings or arrays into one array but none of them worked. I would really appreciate if some of you can help me out. Here is the code:

@IBAction func buttonIsPressed(_ sender: Any) {
    var newitems = textField.text!.components(separatedBy: CharacterSet(charactersIn: ", []()\n.:"))
    print(newitems)
        if newitems.contains(""){
            newitems.removeAll { $0 == ""}
            UserDefaults.standard.set(newitems, forKey: "items")
            print(newitems)
        }else{
            let newitems = textField.text!.components(separatedBy: CharacterSet(charactersIn: ", []()\n.:"))
            UserDefaults.standard.set(newitems, forKey: "items")
        }

        textField.text = ""

        }
  • Well, your initial premise is wrong from the get-go. "which is then turned into an array with the press of a button (indicated by an IBAction buttonIsPressed) and transferred onto a tableView in the next view controller with the help of UserDefaults" No. UserDefaults is not how to transfer data to a tableview in the next view controller. – matt Jul 16 '19 at 22:47
  • Possible duplicate of [How do I concatenate or merge arrays in Swift?](https://stackoverflow.com/questions/25146382/how-do-i-concatenate-or-merge-arrays-in-swift) – Nathan Jul 16 '19 at 22:57

1 Answers1

0

First: you shouldn't use userdefaults for temporary storage

UserDefaults.standard.set(newitems, forKey: "items")

unless you save them for next launch

Second: create an array inside the source vc like

var arr = [String]()

and append to it the latest content

arr += newitems 

then pass arr to the destination vc

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87