Swift 2.0 元组,许多赋值

Swift 2.0 tuple, many assignments

if let (metadata, url) = response, data = NSData(contentsOfURL: url), image = UIImage(data: data) {

来源:https://github.com/dropbox/PhotoWatch/blob/master/PhotoWatch/PhotoViewController.swift

我对这种语法有点困惑,想知道是否有人可以帮助我。

我得到的是: 我知道 if let 是为变量赋值,如果该值存在并且 (metadata, url) 是一个元组。

我不明白的是: 有三个等号和许多逗号 什么值被赋值在哪里?

这部分只是大多重赋值(3个变量):

(metadata, url) = response, data = NSData(contentsOfURL: url), image = UIImage(data: data)

(metadata, url) 正在获取 "response"、数据 "NSData(contentsOfURL: url)" 和图像 "UIImage(data: data)"

这很方便,因为可以在 declaration/assignment 之后立即使用变量。

"if" 子句正在查找整个赋值,就好像它是一个单独的赋值一样。

您的 if let 代码片段说明了可怕的、不可读的代码格式。一种正确的格式是:

if let (metadata, url) = response, 
    data  = NSData(contentsOfURL: url), 
    image = UIImage(data: data) {
  // Use the four bound variables
}
else {
  // One or more of the four are nil
}

如果所有绑定变量都不是nilif let语法形式将执行'consequent';否则执行 'alternate'。

带有 ,if let 语法是较新的 Swift 语法。过去一次只能分配一个任务。人们这样写代码:

if let (metadata, url) = response {
  if let data  = NSData(contentsOfURL: url) {
    if let image = UIImage(data: data) {
      // Use the four bound variables
    }
// lots of `else` clauses; a big mess...
}