Kahsn Kahsn - 4 years ago 826
Swift Question

Accessing a static variable and setting it outside the class

Here is a SubtitleCustomField class.

Class SubtitleCustomField: CustomCellField {
static var CellIdentifier: String!

override init(frame: CGRect) {
super.init(frame: frame)
if CellIdentifier == "A" {
//DO SOMETHINIG
} else if CellIdentifier == "B" {
//DO SOMETHING
}

}
}


Outside SubtitleCustomField class, I basically need to access static variable CellIdentifier, set value like "A", and trigger if statement to run.

In another class, Custom class, I've confirmed that I can access the static variable, Cell Identifier, in a following way:

Class Custom: CustomViewController {
SubtitleCustomField.CellIdentifier = "part1_subtitle"
}


I face a problem at this point. In SubtitleCustomField class, I get an error on
if CellIdentifier == "A"
saying


Static member 'CellIdentifier' cannot be used on instance of type
'SubtitleCustomField'


What would be the best approach I can use to achieve what I want? In summary, I want to set CellIdentifier variable outside
'SubtitleCustomField'
and trigger if statement with the value I set in
'SubtitleCustomField'
class.

Answer Source

The error message is trying to tell you that you are referring to a type property (static property) as if it was an instance property. You need to preface "CellIdentifier" with "SubtitleCustomField" in your SubtitleCustomField initializer just like you do when referring to it elsewhere.

override init(frame: CGRect) {
    super.init(frame: frame)
    if SubtitleCustomField.CellIdentifier == "A" {
        //DO SOMETHINIG
    } else if SubtitleCustomField.CellIdentifier == "B" {
        //DO SOMETHING
    }
}

You should always refer to type properties using the type name followed by "." followed by the property name.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download