Search code examples
swiftxcodesegue

Prepare For Segue With Array - Xcode 8.0 Swift 3.0


What is the best way to add an item to an array on one VC and then use "prepare for segue" to transfer the array to another VC? So far this is what I have managed to come up with: (VC1)

var items: [String] = ["Hello"]

(VC2):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    var destViewController: ViewController = segue.destination as! ViewController
    destViewController.items = [textField.text!]
    items.append(textField.text!)
}

On VC2 an error is coming up that states, "use of unresolved identifier" on the line

items.append(textField.text!)

Solution

  • I am pretty new to iOS/Swift but I recently ran into the same situation. Here is how I do it.

    SourceViewController.swift

    class SourceViewController: UIViewController {
        let stringToPass = "Hello World"
    
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            let destinationVC = segue.destination as! DestinationViewController
            destinationVC.receivedString = stringToPass
            }
        }
    

    DestinationViewController.swift

    class DestinationViewController: UIViewController {
    
        var receivedString: String?
    
        if let newString = receivedString {
            print(newString)
        }
    ...
    

    I realize this is slightly different than your example, but the important thing to note is that when you create "destinationVC" you are then able to modify the properties of it. The key difference is you have to provide the scope of the variable (destinationVC.receivedString) when assigning a value or in your case appending to an array:

    destViewController.items.append(textField.text!)
    

    Without providing the scope Xcode is unable to find the variable (identifier) you are trying to modify since it wasn't part of the current file or part of an import.