swift元组的分解

在这里例子中 (404,”Not Found”)是一个描述HTTP状态码的元组。 HTTP状态码是在请求网页的时候由服务器返回的,404 Not Found表示请求的网页不存在。

  1. let http404Error = (404, "Not Found")
  2. // http404Error is of type (Int, String), and equals (404, "Not Found");

(404,”Not Found”) 将 Int(数字)和String(描述)组合在一起描述HTTP的状态码。可以这么说明:(Int,String)元组类型。你可以通过元组创建任意类型的排列,并且可以包含任意数量的不同类型,比如你可以创建 (Int,Int,Int) 或者 (String,Bool) 或者任意其他你需要的排列组合。你也可以分解元组的内容到常量或者变量中,然后进行访问。

  1. let (statusCode, statusMessage) = http404Error
  2. println("The status code is \(statusCode)")
  3. // prints "The status code is 404"
  4. println("The status message is \(statusMessage)")
  5. // prints "The status message is Not Found";

如果你仅需要元组中得某些数值,那么在分解元组的时候使用下划线来忽略其他的部分:

  1. let (justTheStatusCode, _) = http404Error
  2. println("The status code is \(justTheStatusCode)")
  3. // prints "The status code is 404"。
posted @ 2015-10-28 13:52  小魔浩  阅读(70)  评论(0编辑  收藏  举报