swift元组的分解
在这里例子中 (404,”Not Found”)是一个描述HTTP状态码的元组。 HTTP状态码是在请求网页的时候由服务器返回的,404 Not Found表示请求的网页不存在。
- let http404Error = (404, "Not Found")
- // http404Error is of type (Int, String), and equals (404, "Not Found");
(404,”Not Found”) 将 Int(数字)和String(描述)组合在一起描述HTTP的状态码。可以这么说明:(Int,String)元组类型。你可以通过元组创建任意类型的排列,并且可以包含任意数量的不同类型,比如你可以创建 (Int,Int,Int) 或者 (String,Bool) 或者任意其他你需要的排列组合。你也可以分解元组的内容到常量或者变量中,然后进行访问。
- let (statusCode, statusMessage) = http404Error
- println("The status code is \(statusCode)")
- // prints "The status code is 404"
- println("The status message is \(statusMessage)")
- // prints "The status message is Not Found";
如果你仅需要元组中得某些数值,那么在分解元组的时候使用下划线来忽略其他的部分:
- let (justTheStatusCode, _) = http404Error
- println("The status code is \(justTheStatusCode)")
- // prints "The status code is 404"。