English 中文(简体)
Swift - Tuples
  • 时间:2024-12-22

Swift - Tuples


Previous Page Next Page  

Swift 4 also introduces Tuples type, which are used to group multiple values in a single compound Value.

The values in a tuple can be of any type, and do not need to be of same type.

For example, ("Tutorials Point", 123) is a tuple with two values, one of string Type, and other is integer type. It is a legal command.

let ImplementationError = (501, "Not implemented") is an error when something on the server is not implemented, It returns two values. Error Code, and Description.

You can create tuples from as many values as you want and from any number of different data types.

Here’s the syntax of Tuple declaration −

var TupleName = (Value1, value2,… any number of values)

Here’s a Tuple declaration −

var error501 = (501, “Not implemented”)

You can access the values of tuple using the index numbers that start from 0.

Here’s an example of accessing tuple Values −

print(“The code is(error501.0)”)
print(“The definition of error is(error501.1)”)

You can name the variables of a tuple while declaring , and you can call them using their names

var error501 = (errorCode: 501, description: “Not Implemented”)
print(error501.errorCode)   // prints 501.

Tuples are helpful in returning multiple values from a function. Like, a web apppcation might return a tuple of type ("String", Int) to show whether the loading was successful or failed.

By returning different values in a tuple we can make decisions depending on different tuple types.

Note − Tuples are useful for temporary values and are not suited for complex data.

Advertisements