0

Facing issue while using getter and setter method, that is to be All paths through this function will call itself.

import Foundation

struct FirebaseUser
{
    var student_class_id1 : Int
    {
        get
        {
            return self.student_class_id1
        }
        set(newstudent_class_id1)
        {
            self.student_class_id1 = newstudent_class_id1
        }

    }
    var name: String
    {
        get
        {
            return self.name
        }
        set(newName)
        {
            self.name = newName
        }
    }
    //var school_id: Int?

    var school_id: Int
    {
        get
        {

            return self.school_id
        }
        set(newSchoolId)
        {
            self.school_id = newSchoolId
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Meet Soni
  • 25
  • 2
  • 8

1 Answers1

2

There is no reason for you to define your properties like this. The error is warning you of serious problems. Look at each getter. Your implementation is to call the getter you are trying to define. This will result in infinite recursion. Same with the setter. It calls itself to set the value. Again, infinite recursion. Hence the error.

Since all you need are plain stored properties, your entire struct can be:

struct FirebaseUser
{
    var student_class_id1 : Int
    var name: String
    var school_id: Int
}

Only use get and set blocks when defining a computed property. You want regular stored properties in this case.

If you have a need to perform an action when setting a property value, use willSet and/or didSet.

For example:

var name: String {
    didSet {
        print(name)
    }
}

That is still a plain stored property but it will print the new name anytime it is set.

And it is standard to use lower camelcase for naming variables so it should be:

struct FirebaseUser
{
    var studentClassId1 : Int
    var name: String
    var schoolId: Int
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579