Swift可选语法

时间:2019-01-22 18:19:31

标签: swift optional

我写了一些有效的代码,但是使用了太多强制展开。所以我修复了它,但是必须有更好的方法...

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

3 个答案:

答案 0 :(得分:2)

更好的方法是将photos数组声明为非可选

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

答案 1 :(得分:1)

一次解包photoArray,其余代码要简单得多:

if let photoArray = photoArray {
    for i in photoArray.indices {
        photoButton[i].setImage(UIImage(data: photoArray[i].imageData), for: .normal)
    }
}

如果imageData是可选的,则您需要:

if let photoArray = photoArray {
    for i in photoArray.indices {
        if let imageData = photoArray[i].imageData {
            photoButton[i].setImage(UIImage(data: imageData), for: .normal)
        }
    }
}

行:

photoArray = Array(currentTask?.photos) as? [Photo]

可能写为:

photoArray = currentTask?.photos

但是如果没有有关类型的更多详细信息,就很难确定。

答案 2 :(得分:1)

如果先从可选阵列中取出阵列,这可能会更清洁

您也不必检查count是否大于0,因为如果数组为空(count = 0),则for循环甚至不会运行。

if let array = photoArray {
    for i in array.indices {
        photoButton[i].setImage(UIImage(data: array[i].imageData), for: normal)
    }
}

我不知道Photo类,但是如果imageData也可选,那么:

if let array = photoArray {
    for i in array.indices {
        if let photoData = array[i].imageData {
            photoButton[i].setImage(UIImage(data: photoData), for: .normal)
        }
    }
}