如何使用 3d 数组作为 Swift 中 UICollectionView 的数据源?

How can I use a 3d array as a datasource for a UICollectionView in Swift?

我有一个数据源,它是一个三维数组。

我使用第一个维度计数作为部分数。

我使用三维作为每个部分的项目。

这是一些示例数据:

let sentence1 = [word1, word2, word1] // These are Word objects
let sentence2 = [word1, word2, word3] // in my model.
let sentence3 = [word4, word5, word3]

let paragraph1 = [sentence1, sentence2] // These are Sentence objects.
let paragraph2 = [sentence1, sentence3]

let article = [paragraph1, paragraph2]

目前我刚刚复制了一个3dArray,并将第二维和第三维展平为一维,从而使三维数组成为二维数组。然后我返回 new2dArray.count 作为 numberOfSectionsInCollectionView 并在 cellForItemAtIndexPath 中制作单元格,像这样:

let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as UICollectionViewCell

let cellLabel = new2dArray[indexPath.section][indexPath.row]

但是,在我的 didSelectItemAtIndexPath 中,我需要访问 3dArray 的第二维。我正在寻找这样的东西:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    println("did select cell \(indexPath.row) inside of \(secondDimension) inside of \(indexPath.section)")

我需要做什么?

根据我的评论,为什么不尝试字典数组,其中每个字典代表一个部分,并且在字典中您可以存储一个数组来表示该部分中的行。这是一些伪代码:

// The items in the array under 'kRowData' represent each individual cell, this maybe a value, a model object, or even another dictionary
let sectionOne = ["kRowData" : [1,2,3,4,5,6]]
let sectionTwo = ["kRowData" : [1,2,3,4,5,6]]
let sectionThree = ["kRowData" : [1,2,3,4,5,6]]

let sectionData = [sectionOne,sectionTwo,sectionThree]

sectionData.count // your number of sections
sectionData[indexPath.section]["kRowData"].count // your number of rows in section

我是这样解决这个问题的:

  1. 部分展平 3d 数组,使其成为可用作集合视图数据源的 2d 数组。
  2. 找出 twoDimensionalArray[indexPath.section][indexPath.row] 的索引,如果该数组也被展平。 ()
  3. 计算 threeDimensionalArray 中的元素数量,然后像这样保存各个索引:

    func find3dIndex(article: Array<Array<Array<String>>>, flatWordIndex: Int) -> (Int, Int, Int) {
            var fullSentenceArray = [String]()
            var counter = 0
    
            for index in 0...flatWordIndex {
                for (paragraphIndex, paragraph) in enumerate(article) {
                    for (sentenceIndex, sentence) in enumerate(paragraph) {
                        for (wordIndex,word) in enumerate(sentence) {
                            if counter == flatWordIndex {
                                println("tuple: \(paragraphIndex), \(sentenceIndex), \(wordIndex)")    
                                return (paragraphIndex, sentenceIndex, wordIndex)    
                                break
                            }
                            counter += 1
                        }
                    }
                }
            }
        return (99,99,99)
     }