可选绑定功能与可选链接有何不同?

Hon*_*ney 3 optional swift

编辑:

我正在学习Raywenderlich的教程.我的问题是为什么我们使用可选的绑定,即if let它有什么区别?为什么我们不能使用可选链接 - 类似于A线和B线?

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("IconCell", forIndexPath: indexPath)
    let icon = icons[indexPath.row]

    cell.textLabel?.text = icon.title // Line A
    cell.detailTextLabel?.text = icon.subtitle // Line B

   if let imageView = cell.imageView, iconImage = icon.image { //Line C
      imageView.image = iconImage
    }
Run Code Online (Sandbox Code Playgroud)

教练的解释是:

当我们实例化图标时,我们会根据字符串获得对图像的引用...如果由于某种原因图像未包含在包中,重命名或删除,则该图标可能没有与之关联的图像.我们必须使用,如果让它确保它在那里.

我仍然不明白其中的区别.

ken*_*ytm 6

如果你在想

cell.imageView?.image = icon.image  // let's call this Line D
Run Code Online (Sandbox Code Playgroud)

等于C行.

如果cell.imageView不为-nil,icon.image则为零,则D行将通过将其设置为nil来擦除imageView的原始图像.

但是,在C行中,不会输入条件,因此即使icon.image是零也保持原始图像.

C行相当于

if let image = icon.image {
    cell.imageView?.image = image
}
Run Code Online (Sandbox Code Playgroud)

我猜你的教授只是想让它更明确.