- Swift Tutorial
- Swift - Home
- Swift - Overview
- Swift - Environment
- Swift - Basic Syntax
- Swift - Data Types
- Swift - Variables
- Swift - Optionals
- Swift - Tuples
- Swift - Constants
- Swift - Literals
- Swift - Operators
- Swift - Decision Making
- Swift - Loops
- Swift - Strings
- Swift - Characters
- Swift - Arrays
- Swift - Sets
- Swift - Dictionaries
- Swift - Functions
- Swift - Closures
- Swift - Enumerations
- Swift - Structures
- Swift - Classes
- Swift - Properties
- Swift - Methods
- Swift - Subscripts
- Swift - Inheritance
- Swift - Initialization
- Swift - Deinitialization
- Swift - ARC Overview
- Swift - Optional Chaining
- Swift - Type Casting
- Swift - Extensions
- Swift - Protocols
- Swift - Generics
- Swift - Access Control
- Swift Useful Resources
- Swift - Compile Online
- Swift - Quick Guide
- Swift - Useful Resources
- Swift - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swift - Tuples
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 application 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.