Reputation: 25
I am using a function to add an element to an array using array.append()
. Oddly, the array does not save the element and when checking the count, it will be empty. When putting the same code into a Playground, it will work like it should.
Class 1 (where the function is to add an element):
class FirstClass {
var array:[(Int, Int, String)] = []
func add(var1:Int, var2:Int, var3:String)
{
array.append((Int, Int, String)(var1, var2, var3))
println(array.count)
}
}
Class 2 (from where I call the function):
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
FirstClass().add(1, 2, "xxx")
FirstClass().add(2, 1, "xxx")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I can see that the array is empty, because I always print the count after every adding.
Has anyone else experienced something like that?
Upvotes: 0
Views: 221
Reputation: 72750
You are creating an instance of FirstClass
each time you add an element to the array, so the previous one is lost. You should create one instance only of FirstClass
, and call the add
method on that:
var firstClass = FirstClass()
firstClass.add(1, 2, "xxx")
firstClass.add(2, 1, "xxx")
If you want firstClass
to be persisted in the class instance, declare it as a property:
class ViewController: UIViewController {
var firstClass = FirstClass()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.firstClass.add(1, 2, "xxx")
self.firstClass.add(2, 1, "xxx")
}
}
Upvotes: 2