Attribute a different value to a variable depending on the class from which you are coming (Swift)

Viewed 47

In my HomeClass there is a static var globalLimit: Int = 0 and i have to pass his value in other classes, this is my prepare function

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {



           if let vc = segue.destination as? SelectClass {
                  vc.limit = Int(steppeR.value)
                  HomeClass.globalLimit = Int(steppeR.value)
                  HomeClass.globalRadiusLimit = Int(stepperRadius.value) 
        }
           else if let np = segue.destination as? CourseClass2 {
            np.categories = filteredList
            np.numberPlaces = filteredList.count
            np.radius = Int(stepperRadius.value)
        }

    }

now the problem is this, in my CourseClass2 class that i can even reach from SelectClass i have the var numberPlaces = 0 and his value is

override func viewDidLoad() {
        super.viewDidLoad()

        numberPlaces = HomeClass.globalLimit

    }

but like you can see in my prepare function when i come in CourseClass2 directly from HomeClass i want that the value of numberPlaces = filteredList.count but of course it does not work because it goes against it numberPlaces = HomeClass.globalLimit in the viewDidload of CourseClass2, so how can i solve this problem?

1 Answers

Try in this way:

Set your numberPlaces var as optional:

var numberPlaces: Int?

Then check in view did load if it is nil:

override func viewDidLoad() {
    super.viewDidLoad()

    if numberPlaces == nil {
        numberPlaces = HomeClass.globalLimit
    }
}
Related