官术网_书友最值得收藏!

  • Mastering Swift
  • Jon Hoffman
  • 299字
  • 2021-07-16 14:12:14

Tuples

Tuples groups multiple values into a single compound value. Unlike arrays and dictionaries, the values in a tuple do not have to be of the same type. The following example shows how to define a tuple:

var team = ("Boston", "Red Sox", 97, 65, 59.9)

In the preceding example, we created an unnamed tuple that contains two strings, two integers and one double. We can decompose the values from this tuple into a set of variables, as shown in the following example:

var team = ("Boston", "Red Sox", 97, 65, 59.9)
var (city, name, wins, loses, percent) = team

In the preceding code, the city variable will contain Boston, the name variable will contain Red Sox, the wins variable will contain 97, the loses variable will contain 65, and, finally, the percent variable will contain 0.599.

To avoid this decomposing step, we can create a named tuple. A named tuple associates a name (key) with each element of the tuple. The following example shows how to create a named tuple:

var team = (city:"Boston", name:"Red Sox", wins:97, loses:65, percent:59.9)))

To access the values from a named tuple, we use a dot syntax. In the preceding code, we will access the city element of the tuple like this: team.city. In the preceding code, the team.city element will contain Boston, the team.name element will contain Red Sox, the team.wins element will contain 97, the team.loses element will contain 65, and, finally, the team.percent element will contain 59.9.

Note

Tuples are very good for storing temporary groups of related data or for returning a group of data from a method. Tuples should not be used to persist complex data. If we need to create and pass complex data types within our application, we should model it as a class or structure.

主站蜘蛛池模板: 大名县| 秀山| 横峰县| 张家川| 广饶县| 迁西县| 宜章县| 吴忠市| 浦北县| 邢台市| 前郭尔| 荥阳市| 静宁县| 大荔县| 勐海县| 甘洛县| 彭山县| 启东市| 讷河市| 天镇县| 肇源县| 沅陵县| 荔浦县| 稷山县| 新余市| 上杭县| 锦屏县| 无锡市| 渑池县| 兰坪| 昌图县| 惠东县| 西充县| 大邑县| 建水县| 贵州省| 博乐市| 卓资县| 易门县| 南雄市| 萍乡市|