I needed to create a variable that stored the values that I was introducing in the class each time I instantiated it.
In this way, with the creation of an object, I introduced values to an array and I wanted all the values introduced to the array to be counted every time the class was instantiated.
Thanks to @JoakimDanielson for his answer to use static variables I got it.
This is the code:
import UIKit
class Task{
var tasks = [String]()
static var tasksIntroduced:Int = 0
static var numberInstances = 0
static var tasksCounter:Int = 0
func giveMeTasksName(){
for value in tasks{
print ("Calling giveMeTaskName function -> The values of the tasks are: \(value)")
}
}
func giveMeNumberTasksObject(){
print("Calling giveMeNumberTasksObject function -> The value of the numbers of tasks in object are: \(Task.tasksIntroduced)")
}
func giveMeNumberTotalTasks(){
//Task.tasksCounter = Task.numberInstances * Task.tasksIntroduced
print ("Calling giveMeNumberTotalTasks function -> The tasksCounter variable value is: \(Task.tasksCounter)")
}
init(tasks:[String]){
self.tasks = tasks
Task.tasksIntroduced = tasks.count
Task.tasksCounter = Task.tasksIntroduced + Task.tasksCounter
//Task.numberInstances += 1
}
}
print ("--- Object 1 ---")
var taskObject1 = Task(tasks:["washing clothes", "cleaning the house"])
taskObject1.giveMeNumberTasksObject()
taskObject1.giveMeNumberTotalTasks()
print ("--- Object 2 ---")
var taskObject2 = Task(tasks: ["studying"])
taskObject2.giveMeNumberTasksObject()
taskObject2.giveMeNumberTotalTasks()
print ("--- Object 3 ---")
var taskObject3 = Task(tasks: ["watering the plants", "shopping"])
taskObject3.giveMeNumberTasksObject()
taskObject3.giveMeNumberTotalTasks()
print ("--- Object 4 ---")
var taskObject4 = Task(tasks: ["study physics", "studying maths", "studying project management"])
taskObject3.giveMeNumberTasksObject()
taskObject3.giveMeNumberTotalTasks()
And this is the result:
--- Object 1 --- Calling giveMeNumberTasksObject function -> The value of the numbers of tasks in object are: 2 Calling giveMeNumberTotalTasks function -> The tasksCounter variable value is: 2 --- Object 2 --- Calling giveMeNumberTasksObject function -> The value of the numbers of tasks in object are: 1 Calling giveMeNumberTotalTasks function -> The tasksCounter variable value is: 3 --- Object 3 --- Calling giveMeNumberTasksObject function -> The value of the numbers of tasks in object are: 2 Calling giveMeNumberTotalTasks function -> The tasksCounter variable value is: 5 --- Object 4 --- Calling giveMeNumberTasksObject function -> The value of the numbers of tasks in object are: 3 Calling giveMeNumberTotalTasks function -> The tasksCounter variable value is: 8
Blockquote