Swift - 元組



元組用於在一個值中儲存一組值,例如 (32, "Swift Programming") 是一個包含兩個值的元組,這兩個值分別是 23 和 "Swift Programming"。元組可以儲存多個值,每個值之間用逗號分隔。它可以儲存相同或不同資料型別的值。當我們想要一起返回多個值時,它們很有用。

元組通常由函式用於同時返回多個值。元組不用於複雜的資料結構;它們對於簡單的相關資料組很有用。

語法

以下是元組的語法:

var myValue = (value1, value2, value3, value4, …, valueN)

我們可以使用點表示法後跟元素的索引來訪問元組的元素:

var result = tupleName.indexValue

示例

Swift 程式建立並訪問元組的元素。

import Foundation

// Creating a tuple
var myTuple = ("Romin", 321, "Delhi")

// Accessing the elements of Tuple
var name = myTuple.0
var id = myTuple.1
var city = myTuple.2

// Displaying the result
print("Employee name =", name)
print("Employee id =", id)
print("Employee city =", city)

輸出

Employee name = Romin
Employee id = 321
Employee city = Delhi

包含不同資料型別的元組

在元組中,我們允許儲存不同型別的的資料,例如 (Int, Int, Float),(Float, Double, String) 等。您還可以儲存相同資料型別的資料,例如 (Int, Int, Int) 等。

示例

Swift 程式建立包含不同資料型別的元組。

import Foundation

// Creating a tuple with data of different data types
var myTuple = ("Mona", 21, "Mumbai", 101)

// Accessing the elements of Tuple
var name = myTuple.0
var age = myTuple.1
var city = myTuple.2
var id = myTuple.3

// Displaying the result
print("Student name =", name)
print("Student age =", age)
print("Student city =", city)
print("Student id =", id)

輸出

Student name = Mona
Student age = 21
Student city = Mumbai
Student id = 101

將元組賦值給單獨的變數

我們可以將元組的值分配給單獨的常量或變數,以便我們可以使用該常量或變數的名稱來訪問它們。這裡常量或變數的數量應等於元組的值。

語法

以下是將元組值分配給單獨的常量或變數的語法:

let (name1, name2) = tuple

示例

Swift 程式建立一個元組,其值分配給一組常量。

import Foundation

// Creating a tuple
var myTuple = ("Mickey", 21, "Pune")

// Assigning tuple to a set of constants
let(name, age, city) = myTuple

// Accessing the value of tuples according to the constant
print("Student name =", name)
print("Student age =", age)
print("Student city =", city)

輸出

Student name = Mickey
Student age = 21
Student city = Pune

Swift 中帶下劃線的元組

我們允許在元組中使用下劃線 "_"。它會在分解元組時忽略帶下劃線的部分元組。或者換句話說,我們可以說透過使用下劃線,我們可以忽略某些元組的值。我們允許在同一個元組中使用多個下劃線來忽略多個值。

語法

以下是帶下劃線的元組的語法:

let (name1, name2, _) = tuple

示例

Swift 程式建立一個帶下劃線 "_" 的元組。

import Foundation

// Creating a tuple
var myTuple = (21, "Pune", "CSE")

// Assigning a tuple to a set of constants
let(age, _, branch) = myTuple

// Accessing the values of tuples 
print("Student age =", age)
print("branch =", branch)

輸出

Student age = 21
branch = CSE

為元組中的各個值分配名稱

在 Swift 中,我們允許為元組的各個元素分配名稱。我們還可以根據其名稱訪問元組的元素。

語法

以下是為元組元素分配名稱的語法:

let myTuple = (id: 102, name: "Sona")

示例

Swift 程式建立並根據其名稱訪問元組元素。

import Foundation

// Creating a tuple
var myTuple = (name: "Mona", branch: "ECE", year: 2022) 

// Accessing the values of tuples according to their names
print("Student name =", myTuple.name)
print("Branch =", myTuple.branch)
print("Current Year", myTuple.year)

輸出

Student name = Mona
Branch = ECE
Current Year 2022
廣告