gpt4 book ai didi

arrays - 具有惰性元素的数组

转载 作者:搜寻专家 更新时间:2023-11-01 06:17:15 24 4
gpt4 key购买 nike

我想知道 Swift 3 编程语言中是否有一种构造允许我将一些对象存储在数组中,但延迟地初始化该数组中的每个元素。

想象一下这个示例类:

class A {
let test = "hello"
let test2 = 2.0
}

现在我想将一个“A”对象数组存储在另一个类的数组中,如下所示:

class B {
var lazy(?) array: [A] = {
// Some code to initialize the element being accessed
}()
}

如果我现在访问任何元素,如果它在我访问它的时候初始化它会很酷,所以很懒

print(B.array[1].test) (element at index one is now initialized)

这可能吗?

最佳答案

您可以为 A 使用 lazy 后备存储,它在第一次访问时实例化,例如:

class Astorage {
/* ... lots of ... */
let id: Int
var foo: String = "bar"
init(_ id: Int) {
self.id = id
print("Initializing backing storage for A with id \(id)")
// ...
}
}

class A {
private let id: Int
lazy var storage: Astorage = Astorage(self.id)
init(_ id: Int) {
self.id = id
}
}

class B {
var array: [A]
init (_ array: [A]) {
self.array = array
}
}

let b = B((1...5).map(A.init))

b.array[2].storage.foo = "foo"
// Initializing backing storage for A with id 3

b.array[4].storage.foo = "bax"
// Initializing backing storage for A with id 5

关于arrays - 具有惰性元素的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41789301/

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