Search code examples
arraysswiftnsdata

How to append an empty value to NSData Array (Swift)


I have

var images: [NSData] = [];

and I need to add empty values into this array during executing of my for-loop block and then replace these empty values on NSData of the images I downloaded from the server.

How should I append an empty value to NSData-array?

I tried some like ... as! NSData, or create variable someVar: NSData? - app crashes every time


Solution

  • You could have your array be optional NSData like so:

    var images: [NSData?] = [];
    

    That way, you can set nil if you want:

    images.append(nil)
    

    And check on the loop:

    for imageData in images {
        if let data = imageData {
            // data exists
        } else {
            // data doesn't exist yet at this index
        }
    }