alionthego
alionthego

Reputation: 9743

how can I pass a swift array by reference between viewControllers in prepare(for segue:?

I know that swift array structs are copied by value and not reference. Is there a simple way that I can cast or otherwise pass the array by reference in my prepare(for segue:... method so that I may pass a reference to the array from viewController A to viewController B?

I have seen some answers that refer to passing an array to a function but I simply want to pass it to other viewControllers

Upvotes: 0

Views: 638

Answers (5)

congsun
congsun

Reputation: 144

If you cast the array into NSArray it should do the work.

Upvotes: 0

farshad jahanmanesh
farshad jahanmanesh

Reputation: 1

create a global array like this

var myGlobalArray = [Int]()
class viewControllerA : UIViewController {

}

now you can use it everywhere. but this is not a good thing

Upvotes: 0

Jhony
Jhony

Reputation: 187

If u want to transfer array from one controller to another controller using segue create array in your first controller like this

 var dataSource : [ANY MODEL CLASS] = []

use this method to transfer your data using segue

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "YOURSEGUE") {
            let vc = segue.destination as! YOUCONTROLLER
             vc.myArray = self.dataSource
        }

in your second controller create same type array

  var myArray : [ANY MODEL CLASS] = []

so now when you moved to another controller using this "YOURSEGUE" segue your array will have data

Upvotes: 0

Nancy Madan
Nancy Madan

Reputation: 447

Yes you can achieve it by passing the values from viewController A to viewController B. All you need to do is, take an array (arrB) in ViewController B .

let VB = self.storyboard?.instantiateViewController(withIdentifier: "viewControllerB") as! viewControllerB
vc.arrA = arrA
 self.navigationController?.pushViewController(vc, animated: true)

This will not pass reference but the values of area to arrB.

Upvotes: 0

shio
shio

Reputation: 408

Create wrapper class for your array and then pass that class reference wherever you want:

class ArrayWrapper {
    let array: [YourType]

    init(array: [YourType]) {
        self.array = array
    }
}

Upvotes: 1

Related Questions