Swift:类和属性 - 所有只初始化一次

时间:2015-04-10 12:38:04

标签: class swift struct static singleton

我希望拥有一个具有属性的类或结构(无关紧要),其中所有内容都只能在应用程序中初始化一次。任何修改类或其属性的尝试都将失败或无法实现。

这可能吗?

到目前为止,我已经提出了这个问题:

public struct ScreenInfo
{
    static var scaleFactor:Int = 0

    public init(initialScaleFactor:Int)
    {
        if (ScreenInfo.scaleFactor == 0) {
            ScreenInfo.scaleFactor = initialScaleFactor
        }
    }

    public static func getScaleFactor()
    -> Int
    {
        return scaleFactor
    }
}

let si1:ScreenInfo = ScreenInfo(initialScaleFactor:11)
ScreenInfo.getScaleFactor()    // = 11

let si2:ScreenInfo = ScreenInfo(initialScaleFactor:22)
ScreenInfo.getScaleFactor()    // = 11

1 个答案:

答案 0 :(得分:1)

你想要的有点不寻常,但它是可能的。

public struct ScreenInfo {
  private static var _scaleFactor: Int?
  public static var scaleFactor: Int? {
    set {
      if _scaleFactor == nil {
        _scaleFactor = newValue
      } else {
        // Optionally throw an exception or something
      }
    }
    get {
      return _scaleFactor
    }
  }
}

ScreenInfo.scaleFactor       // nil
ScreenInfo.scaleFactor = 5
ScreenInfo.scaleFactor       // 5
ScreenInfo.scaleFactor = 15
ScreenInfo.scaleFactor       // 5