访问静态变量并将其设置在 class 之外

Accessing a static variable and setting it outside the class

这是一个 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
  }

  }
}

在 SubtitleCustomField class 之外,我基本上需要访问静态变量 CellIdentifier,将值设置为 "A",并触发 if 语句 运行.

在另一个 class、自定义 class 中,我已确认我可以通过以下方式访问静态变量 CellIdentifier:

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

此时我遇到了一个问题。在 SubtitleCustomField class 中,我在 if CellIdentifier == "A"

时收到错误消息

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

实现我想要的目标的最佳方法是什么?总之,我想在 SubtitleCustomField 之外设置 CellIdentifier 变量,并使用我在 SubtitleCustomField class.

中设置的值触发 if 语句

错误消息试图告诉您您正在引用类型 属性(静态 属性),就好像它是一个实例 属性。您需要在 SubtitleCustomField 初始值设定项中使用 "SubtitleCustomField" 作为 "CellIdentifier" 的前缀,就像您在其他地方引用它时所做的那样。

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

您应该始终使用类型名称后跟“.”来引用类型属性。后跟 属性 名称。