1

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

3 Answers 3

5

Create an empty Data (NSData in Swift 2) instance and append it to the array

var images: [Data] = []
let emptyData = Data()
images.append(emptyData)
Sign up to request clarification or add additional context in comments.

Comments

4

Make an array of optionals var images: [NSData?] = [];
And add nil values when in for-loop images.append(nil)
After that replace with your real data if you know position in array

Comments

3

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.