swift Tuples

前端之家收集整理的这篇文章主要介绍了swift Tuples前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. Tuples
  2.  
  3. Tuples 可以用一对圆括号包裹若干个值,这些值的类型可以互不相同。
  4.  
  5. 例如,(404,"Not Found") 就可以表示一个HTTP状态码.
  6. let http404Error = (404,"Not Found")
  7. http404Error 的类型是 (Int,String),他等于 (404,"Not Found")
  8.  
  9. Tuples中可以包含任意类型
  10.  
  11. 你可以像下面这样赋值
  12. let (statusCode,statusMessage) = http404Error
  13. print("The status code is \(statusCode)")
  14. // 输出 "The status code is 404"
  15. print("The status message is \(statusMessage)")
  16. // 输出 "The status message is Not Found"
  17. 如果只需要Tuples中部分值,其他不需要的值可以用 _ 代替
  18. 例如:
  19. let (justTheStatusCode,_) = http404Error
  20. print("The status code is \(justTheStatusCode)")
  21. // 输出 "The status code is 404"
  22. 你也可以通过下标来获取值,下标从0开始
  23. 例如:
  24. print("The status code is \(http404Error.0)")
  25. // 输出 "The status code is 404"
  26. print("The status message is \(http404Error.1)")
  27. // 输出 "The status message is Not Found"
  28. 你可以给Tuple中个元素取个名字
  29. 例如:
  30. let http200Status = (statusCode: 200,description: "OK")
  31. 这样你就可以直接通过名字获取元素
  32. print("The status code is \(http200Status.statusCode)")
  33. // 输出 "The status code is 200"
  34. print("The status message is \(http200Status.description)")
  35. // 输出 "The status message is OK"
  36. Tuples 可以作为函数的值返回

原文 Tuples
https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309

猜你在找的Swift相关文章