我写了一些有效的代码,但是使用了太多的强制展开。所以我修好了,但必须有更好的方法。。。
var currentTask: Tasks?
var photoArray: [Photo]?
@IBOutlet var photoButton: [TaskImageButton]!
photoArray = Array(currentTask?.photos) as? [Photo]
if photoArray!.count > 0 {
for i in (photoArray?.indices)! {
photoButton[i].setImage(UIImage(data: photoArray![i].imageData!), for: .normal)
}
}
我尝试的解决方案:
if let photoArraySize = photoArray?.count {
if photoArraySize > 0 {
for i in (photoArray?.indices)! {
if let photoData = photoArray?[i].imageData {
photoButton[i].setImage(UIImage(data: photoData), for: .normal)
}
}
}
}
最佳答案
更好的方法是将照片数组声明为非可选
var photoArray = [Photo]()
...
photoArray = (Array(currentTask?.photos) as? [Photo]) ?? []
...
for (index, photoData) in photoArray.enumerated() where photoData.imageData != nil {
photoButton[index].setImage(UIImage(data: photoData.imageData!), for: .normal)
}
关于swift - Swift optional 语法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54314296/