ios - 将 'class variable' 分配给 'lazy var' 内的变量

标签 ios arrays swift uicollectionview lazy-initialization

我试图理解可拖动 Collection View 单元格的逻辑。它适用于虚拟数据,但是我无法弄清楚如何使其适用于真实数据。

我不知道给这个问题起什么标题,请随时编辑/改进它

如果我将这种方法与虚拟数组项一起使用并调用该函数

class TableViewController: UITableViewController, KDRearrangeableCollectionViewDelegate, UICollectionViewDataSource { 

lazy var data : [[String]] = {

    var array = [[String]]()

    let images = [
        "1.jpg", "2.jpg", "3.jpg"
    ]

    if array.count == 0 {

        var index = 0
        var section = 0

        for image in images {
            if array.count <= section {
                array.append([String]())
            }
            array[section].append(image)

            index += 1
        }
    }
    return array
}()

func moveDataItem(fromIndexPath : NSIndexPath, toIndexPath: NSIndexPath) {
    let name = self.data[fromIndexPath.section][fromIndexPath.item]
    self.data[fromIndexPath.section].removeAtIndex(fromIndexPath.item)
    self.data[toIndexPath.section].insert(name, atIndex: toIndexPath.item)

    print(self.data) 
}

此时 print(self.data) 打印拖动/重新排列后数组项的新顺序。

示例 print(self.data) 日志: [["2.jpg", "1.jpg", "3.jpg"]]


现在我有了真实的数据,并且在从数据库中获取数据后,它会被附加到项目中。

var realImages = [NSURL]()

// I tried assigning `images` array inside `lazy var data` but received error: 

lazy var data : [[String]] = { 
    var array = [[String]]()
    let images = realImages    // error here
            ...

Instance member realImages cannot be used on type TableViewController

在这种情况下,使用真实数组的正确方法是什么?


(This explanationits Git repo 非常适合理解它)。我使用虚拟数据进一步简化了它,但我无法理解“惰性变量”和常规“变量”的逻辑以及如何使其在这种情况下工作

最佳答案

您需要像 let images = self.realImages 一样显式使用 self。

lazy var data : [[String]] = { [unonwed self] in
    var array = [[String]]()
    let images = self.realImages    // error gone :)

(请注意,我们必须在这里说 [unowned self] 以防止 strong reference cycle )

关于ios - 将 'class variable' 分配给 'lazy var' 内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36713445/

相关文章:

swift - 快速实现 PHPhotoLibraryChangeObserver 协议(protocol)

ios - 如果当前打开了特定的 ViewController,如何检查 AppDelegate

ios - 当 pointSize 为 0 时,UIFont 未设置正确的字体名称

ios - 如果我创建个人帐户而不是公司帐户,是否可以让多个开发人员测试我的 iPhone/iPad 应用程序?

arrays - 连接字符数组元素

ios - 自定义单元格类中的 init() 是 collectionView 的委托(delegate)和数据源

arrays - 任意数组到字符数组

ios - 运行多个 HealthKit 示例查询的更好方法?

javascript - 是否有可能从多个条件中返回任何一个为真的条件(以一种简单的方式)?

c# - 如何删除一个 int 数组中存在于另一个 int 数组中的所有元素?