我正在寻找具有属性的类或结构(无关紧要),其中所有内容只能在应用程序中初始化一次。修改类或其属性的任何尝试将失败或不可能。
这可能吗?
到目前为止,我已经提出了:
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
最佳答案
您想要的东西有些不寻常,但有可能。
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
关于class - Swift:类和属性-全部仅初始化一次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29561660/