<< Back to SWIFT
Swift Tuple Examples
Use tuples to combine values together. Tuples can be returned from funcs.Tuples. An Int is an Int. A String is a String. Values are separate units. But with tuples, we can combine these units into groups.
Uses. Tuples have many uses in programs. When looping over a dictionary, we access the data as tuples. To return multiple values in a method, we return a tuple.
First example. Here we create a tuple with a String and an Int. We access the first item in the tuple with the expression entry.0. And the second item is at index 1.
Note: To create a tuple, we use a comma-separated list of the values in parentheses.
Further: A tuple can contain more than two elements. But be careful with large tuples—an array may be a better option.
Swift program that uses tuple
// Create a tuple with two items.
let entry = ("cat", 100)
// Access item 0 and item 1.
let name = entry.0
let number = entry.1
// Display name, number and entire tuple.
print(name)
print(number)
print(entry)
Output
cat
100
(cat, 100)
Decompose. A tuple is a "composition" of multiple values. So when we decompose a tuple, we break it apart (unpack it) into its smallest parts.
Underscore: This is a special variable name in Swift. It indicates a variable we will not need to access.
Swift program that unpacks three-item tuple
let color = ("Green", 822, 0)
// Decompose the tuple to unpack its items into variables.
// ... An underscore means no variable.
let (name, code, _) = color
print(name)
print(code)
Output
Green
822
Named tuple. Indexes are fine for some tuples. But for more complex ones, we can provide names for the items in a tuple upon creation. We can then reference those names.
Swift program that uses named items
// Use named items in tuple.
let language = (name: "Ruby", speed: 0, usability: 10)
// Access named items in tuple.
print("\(language.name) has speed of \(language.speed)")
print("\(language.name) has usability of \(language.usability)")
Output
Ruby has speed of 0
Ruby has usability of 10
Multiple return values. To return many values at once, a method can return a tuple. Here we return two Ints from a func. No inout parameters are needed.
Swift program that returns tuple from func
func computeData(x: Int) -> (Int, Int) {
// This func returns a tuple.
return (x * 2, x * 100)
}
// Get tuple from method.
let result = computeData(3)
print(result)
Output
(6, 300)
Switch. A tuple can be switched upon. We specify all the elements in each case in the switch statement. Here is the simplest syntax form.
SwitchTip: Each case in a tuple switch must have the correct "tuple pattern" with a matching number of elements.
Swift program that switches on tuple
let value = ("bird", 100)
// Switch on the tuple.
switch (value) {
case ("bird", 100): print("Bird 100")
default: print("Unknown")
}
Output
Bird 100
Let, switch. This example uses the "let" keyword to capture a value in a tuple switch. The "let animal" value is the first item in a tuple. The second item must be 100 to match.
Swift program that uses let, tuple switch
let value = ("elephant", 100)
// Use let to capture a variable in a tuple.
switch (value) {
case (let animal, 100): print("\(animal) has value 100")
default: print("Default")
}
Output
elephant has value 100
Switch, underscore. This is another tuple switch feature. We can use the underscore to match any value in a tuple's item. We switch on the third item in a tuple in this example.
Swift program that switches on tuple, underscore
let elements = ("aa", "bb", 2)
// Match complete tuple values.
switch (elements) {
case (_, _, 1): print("Third value is 1")
case (_, _, 2): print("Third value is 2")
default: print("Error")
}
Output
Third value is 2
A review. Tuples are a core part of the Swift language. They are used throughout code. They reduce complexity by composing multiple items into one.
Related Links:
- Swift String Append Example: reserveCapacity
- Swift File (Read Text File Into String)
- Swift Find Strings: range of Example
- Swift Subscript Example
- Swift hasPrefix and hasSuffix Examples
- Swift Array of Dictionary Elements
- Swift Tutorial
- Swift Odd and Even Numbers
- Swift Operator: Equality, Prefix and Postfix
- Swift Dictionary Examples
- Swift Class Example: init, self
- Swift Combine Arrays: append, contentsOf
- Swift Initialize Array
- Swift Int Examples: Int.max, Int.min
- Swift 2D Array Examples
- Swift Error Handling: try, catch
- Swift Repeat While Loop
- Swift Optional: Nil Examples
- Swift Replace String Example
- Swift Print: Lines, Separator and Terminator
- Swift inout Keyword: Func Example
- Swift Lower, Uppercase and Capitalized Strings
- Swift enum Examples: case, rawValue
- Swift Padding String Example (toLength)
- Swift UIActivityIndicatorView Example
- Swift UIAlertController: Message Box, Dialog Example
- Swift UIButton, iOS Example
- Swift UICollectionView Tutorial
- Swift UIColor iOS Example: backgroundColor, textColor
- Swift UIFont Example: Name and Size
- Swift UIImageView Example
- Swift UIKit (Index)
- Swift UILabel Tutorial: iPhone App, Uses ViewController
- Swift String
- Swift Remove Duplicates From Array
- Swift If, If Else Example
- Swift Caesar Cipher
- Swift UIStepper Usage
- Swift UISwitch: ViewController
- Swift UITableView Example: UITableViewDataSource
- Swift UITextField: iPhone Text Field Example
- Swift UITextView Example
- Swift UIToolbar Tutorial: UIBarButtonItem
- Swift UIWebView: LoadHtmlString Example
- Swift Var Versus Let Keywords
- Swift Math: abs, sqrt and pow
- Swift Reverse String
- Swift Struct (Class Versus Struct)
- Top 22 Swift Interview Questions (2021)
- Swift Substring Examples
- Swift Switch Statements
- Swift Convert Int to Character: UnicodeScalar, utf8
- Swift Property Examples
- Swift isEmpty String (characters.count Is Zero)
- Swift Recursion
- Swift ROT13 Func
- Swift Convert String to Byte Array: utf8 and UInt8
- Swift Keywords
- Swift Convert String to Int Example
- Swift Join Strings: joined, separator Examples
- Swift String Literal, Interpolation
- Swift Extension Methods: String, Int Extensions
- Swift Characters: String Examples
- Swift Func Examples: Var, Return and Static
- Swift Guard Example: Guard Else, Return
- Swift Fibonacci Numbers
- Swift Trim Strings
- Swift Set Collection: Insert and Contains
- Swift Tuple Examples
- Swift Loops: for, repeat and while Examples
- Swift Split Strings Example (components)
- Swift Array Examples, String Arrays
- Swift UIPickerView Example: UIPickerViewDataSource
- Swift UIProgressView Example: Progress
- Swift UISegmentedControl
- Swift UISlider Example
- Swift Random Numbers: arc4random
- Swift ASCII Table
- Swift Range Examples (index, offsetBy)
- Swift String Length
- Swift Sort String Arrays: Closure Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf