Swift Error "static member cannot be used on instance of type"

12,632

Static members can not be accessed with Instance variables like l and r.

Static members must be accessed through the type (class/struct/enum) name like:

GlobalSettings.rating
Share:
12,632

Related videos on Youtube

Adam
Author by

Adam

Updated on May 25, 2022

Comments

  • Adam
    Adam almost 2 years

    I want to overload the operator for my struct but I get the message "static member 'rating' cannot be used on instance of type 'GlobalSettings'". I already read couple answers to this error but the solutions there don't help me at all. How can I solve this problem?

    struct GlobalSettings{
        static var rating = false
    }
    
    func ==(l: GlobalSettings, r: GlobalSettings) -> Bool {
        if l.rating == r.rating {
            return true
        }else{
            return false
        }
    }
    
    • Alexander
      Alexander over 6 years
      l and r don't have a rating variable. GlobalSettings does.
    • Martin R
      Martin R over 6 years
      The obvious solution would be to remove the "static". Why do you think that rating should be a static property?
    • Martin R
      Martin R over 6 years
      And btw, simplify the function body to return l.rating == r.rating
    • Adam
      Adam over 6 years
      I use the GlobalSettings to keep all settings in my app so they can be accessed anywhere. I believe static variables are good for that but I am a Swift newbie so I am not sure
    • Martin R
      Martin R over 6 years
      Then why do you define == to compare two "global settings", if there are no instances of that type?
    • Adam
      Adam over 6 years
      My idea was to create a "copy" of all variables inside GlobalSettings structure during launching every View Controller and then whenever the VC appears again it checks if the settings where changed, if so then it would refresh some UI elements. I guess I can do it with delegates