richbrz
richbrz

Reputation: 92

Arrays appended inside function not working in other class

My problem is that I have 4 empty arrays:

var Names:[String] = []
var Amounts:[Int] = []
var Dates:[NSDate] = []
var Images:[UIImage] = []

Inside a class NewPersonViewController.

I also have a function inside NewPersonViewController:

func create(){
   Names.append(nameField.text)
   Amounts.append(amountField.text.toInt()!)
   Dates.append(dateToBePaid.date)
}

I call create() when a button is pressed. The function is just a button action, declared inside NewPersonViewController.

My problem: When I print out the arrays in another class (which is in another file) not including Images, I just get this:

[]
[]
[]

Yup, thats my output. Thank you in advance. Side note: I am new to swift :)

Upvotes: 0

Views: 534

Answers (2)

Rick Klenotiz
Rick Klenotiz

Reputation: 1

I'm relatively new here but if you move the arrays out of the ViewController they will become GLOBAL variables and accessible in any other View or Table Controller. I just tried it and it worked just fine.

For Global variables I have always added a prefix of "gl_" so I know for a fact this is a global variable which means they need to be used with care. In general, global variables are risky and IMHO should be used frugally and consider any risks that come from using them...especially security risks.

In my ViewController.swift file:


import UIKit


var gl_Names:[String] = []
var gl_Amounts:[Int] = []
var gl_Dates:[NSDate] = []
var gl_Images:[UIImage] = []


class ViewController: UIViewController {

    @IBOutlet weak var textInput1: UITextField!

    @IBOutlet weak var textInput2: UITextField!

    @IBOutlet weak var textInput3: UITextField!

etc etc

Upvotes: 0

justinpawela
justinpawela

Reputation: 1978

Unless you have just posted some toy code, it seems like there are a lot of problems with your design.

However, the specific problem you may be facing is that, in Swift, Arrays are "value types". Basically it means that if you pass around an Array, Swift is actually making copies every time. So if you edit copy 2 in a different class, it does not affect copy 1 in your original class.

If you just want to get your code working without refactoring to deal with this (and you should really refactor), the easiest thing to do is use NSMutableArray instead of Swift arrays. NSMutableArray is a class, which is a "reference type". You can pass that all around, make changes, and use it from anywhere. Because you are really only passing a "reference", there is only ever one array, and changes you make show up everywhere.

Upvotes: 1

Related Questions