重新排序 UIImage 数组中的元素

Reordering Elements inside Array of UIImage

我有一个 NSURL 数组,我可以使用函数 removeAtIndexinsert。我知道 fromIndexPathtoIndexPath 并且此方法帮助我使用此委托方法为 [[NSURL]] 完成相同的操作(检查下面的 var data):

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)

     // do same for UIImage array
}

但是,我有一个 UIImage 数组,其中包含 3 个空元素 运行ning。

var newImages = [UIImage?]()

 viewDidLoad() {
    newImages.append(nil)
    newImages.append(nil)
    newImages.append(nil)
 }

我的问题是我如何使用moveDataItem()中的newImages数组以及data并能够运行 重新排列 UIImage 数组顺序的行。

我尝试了这些但不幸的是我无法使它们工作..

self.newImages[fromIndexPath.section].removeAtIndex(fromIndexPath.item)
// and
self.newImages[fromIndexPath.row].removeAtIndex(fromIndexPath.item)

为清楚起见,数据数组如下所示

lazy var data : [[NSURL]] = {

    var array = [[NSURL]]()
    let images = self.imageURLsArray

    if array.count == 0 {

        var index = 0
        var section = 0


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

            index += 1
        }
    }
    return array
}()

这应该适用于重新排列任何二维数组:

func move<T>(fromIndexPath : NSIndexPath, toIndexPath: NSIndexPath, items:[[T]]) -> [[T]] {

    var newData = items

    if newData.count > 1 {
        let thing = newData[fromIndexPath.section][fromIndexPath.item]
        newData[fromIndexPath.section].removeAtIndex(fromIndexPath.item)
        newData[toIndexPath.section].insert(thing, atIndex: toIndexPath.item)
    }
    return newData
}

用法示例:

var things = [["hi", "there"], ["guys", "gals"]]

// "[["hi", "there"], ["guys", "gals"]]\n"
print(things)

things = move(NSIndexPath(forRow: 0, inSection: 0), toIndexPath: NSIndexPath(forRow:1, inSection:  0), items: things)

// "[["there", "hi"], ["guys", "gals"]]\n"
print(things)

这将适用于普通数组:

func move<T>(fromIndex : Int, toIndex: Int, items:[T]) -> [T] {

    var newData = items

    if newData.count > 1 {
        let thing = newData[fromIndex]
        newData.removeAtIndex(fromIndex)
        newData.insert(thing, atIndex: toIndex)
    }
    return newData
}