简体   繁体   English

附加图像后,可选的UIImage数组为nil

[英]Optional UIImage array is nil after appending images

I have created an optional UIImage array as the following 我创建了一个可选的UIImage数组,如下所示

var images: [UIImage]?

Then I have a function that receives as parameter an UIImage array: 然后,我有一个函数接收UIImage数组作为参数:

func process(_ images: [UIImage] {
    images.forEach {
        self.images?.append($0)
    }
    print("images nil?:", self.images == nil)
}

Somehow this function prints that my self.images is nil, even after appending objects to it; 该函数以某种方式打印出我的self.images为nil,即使在self.images添加对象之后也是如此。 but if I change my forEach iteration to simply: 但是如果我将forEach迭代更改为:

self.images = images

It now doesn't recognize that the global variable is nil. 现在,它无法识别全局变量为nil。

Why does this happen? 为什么会这样?

您需要初始化一个数组。

var images: [UIImage]? = []

You have never initialised your images array. 您从未初始化过图像数组。 Before appending, please do this: 在附加之前,请执行以下操作:

images = [UIImage]()

Initialize your array like this: 像这样初始化数组:

var images = [UIImage]()

Append the whole array at once like: 一次附加整个数组,例如:

func process(_ images: [UIImage]) {
    self.images.append(contentsOf: images)
    print(self.images)
}

No need to make your array optional. 无需将数组设为可选。 Since if there is no images in the array it would be empty. 由于如果数组中没有图像,则它将为空。 Check for array count instead of making it optional. 检查数组计数,而不是使其为可选。

Just you need to do this 只是你需要这样做

var images = [UIImage]()
func process(_ images: [UIImage] {
    self.images = images
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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