gpt4 book ai didi

swift - 静态变量如何存储在 Swift 的内存中?

转载 作者:IT王子 更新时间:2023-10-29 05:37:43 26 4
gpt4 key购买 nike

Swift 中的静态变量是如何存储的?

  1. 如果我从不调用 func useStaticVar() 会怎样?这些变量有没有初始化?

  2. 如果我调用了 useStaticVar() 然后再也没有访问过它们会怎样?阿

    struct Something {
    static var myVariable = 0
    static let myConstant = 3
    static var myString: String?

    static func useStaticVar() {
    myVariable = myConstant
    myString = String(myVariable)
    }
    }

最佳答案

检查这个: Type Properties

NOTE

Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.

Stored type properties are lazily initialized on their first access. They are guaranteed to be initialized only once, even when accessed by multiple threads simultaneously, and they do not need to be marked with the lazy modifier.

您必须始终为存储的类型属性提供默认值。

您的代码缺少myString 的默认值,在这种情况下,Swift 会为其提供默认的nil

存储类型属性在首次访问时延迟初始化。

您可以测试并查看存储的类型属性是如何使用如下代码初始化的:

func ZeroGenerator() -> Int {
print(#function)
return 0
}

func ThreeGenerator() -> Int {
print(#function)
return 3
}

func NilGeneartor() -> String? {
print(#function)
return nil
}

struct Something {
static var myVariable = ZeroGenerator()
static let myConstant = ThreeGenerator()
static var myString: String? = NilGeneartor()

static func useStaticVar() {
print(#function)
myVariable = myConstant
myString = String(myVariable)
}
}

Something.useStaticVar()

输出:

useStaticVar()
ZeroGenerator()
ThreeGenerator()
NilGeneartor()

编译器可能会对常量默认值进行一些优化,但在语义上没有区别。

关于swift - 静态变量如何存储在 Swift 的内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33177615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com