简体   繁体   中英

Why is my image not being appended to the array?

I've a simple model that includes:

var photos: [UIImage]?

I've copied the file zombies.jpg as a file into the project. Then, in a required init in a Table View Controller, I want to load a dummy record. I can define all the String and NSDate properties, but when I try to append photos:

dummyRecord1.photos?.append(UIImage(named: "zombies.jpg")!)
print(UIImage(named: "zombies.jpg"))
print(dummyRecord1.photos)

The console shows that the image is there, but it never gets into the array:

Optional(<UIImage: 0x7f8fd14b4c40>, {2592, 1936})nil

You have initialize photos array, and you are using conditional unwrapping, which means if its not nil append but your photos array is nil at the time so it will not append a photo in nil array. You should do something like this var photos:[UIImage] = []

Better do this:

var photos : [UIImage?] = []

It initializes an empty array, that is ready to store UIImage objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM