senty senty - 2 years ago 86
Swift Question

Accessing UIImage inside Array with indexPath & Creating Empty UIImage Array Element

I have an array of UIImages. I want to create it with 3 empty empty array elements (of UIImage)

var newImages = [UIImage]()

First Question: How can I get it like this?

let newImages = [emptyUIImage,emptyUIImage,emptyUIImage]

Or is there a way to store empty array element for UIImage array, as I stored like this, empty NSURL for NSURL array?

if data.count != 3 {
let emptyURL = NSURL(string: "")

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

Second question: How can I use this function for my UIImages and keep track of array elements?

I tried these but I couldn't figure out how to use it with my UIImage array.


To add:

The data lazy var handles first initialisation of the images and also allows for modification, using URLs fetched from the database.

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 {

index += 1
return array

I use this data for creating and manipulating CollectionViewCells. Using this data, I allow them to be draggable/rearrangeable while keeping track and this function helps me create the new structure (of indexes) of the images.

Answer Source

You can create an array of any type with a fixed number of elements and then use array[i] = value to set the value for the ith index in your array

//instead of passing 10 you could pass, for example, array.count
  var images = [UIImage](count: 10, repeatedValue: nil)

images[0] = //someImage
images[3] = //someImage
images[1] = //someImage

Alternatively you could make your array an array of optional UIImages like this...

var newImages = [UIImage?]()

and then append nil where there is an empty image...


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download