0

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

1
  • You could use NSArray... Commented Aug 3, 2018 at 11:01

5 Answers 5

1

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
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

probably best to change to var array: [YourType] as I guess most often the passed array will need to be mutated. but thanks for your answer. it's what I was looking for. Also good to note that multiple arrays can be held in this wrapper class if necessary. thx.
0

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.

Comments

0

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.