arrays - 具有惰性元素的数组

标签 arrays swift lazy-initialization

我想知道 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/

相关文章:

javascript - 在Javascript中将具有树结构的数组转换为对象

java - 在惰性初始化供应商中引用 "this"?

swift - Bundle.classNamed(_ 类名 : String) fails but NSClassFromString() work

swift - Swift 中的惰性变量是否被多次计算?

c++ - 如何在不可变的 C++ 对象中实现延迟初始化和缓存?

数组中的 C 链表

arrays - 设置数组(记录)长度时,Delphi 堆栈溢出和访问冲突错误

java - 获取数组中字符串的索引,并在另一个数组中删除这些索引处的字符串

swift - UITextField 键盘返回按钮标题

swift - 为什么 UISearchBar 在 Swift 中跳下并覆盖/重叠第一行?