Skip to content

[Swift 6]: Reworked tuples and its exercise #831

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion concepts/tuples/.meta/config.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{
"blurb": "Tuples are used to combine multiple values into a single compound value where each of the values may have a different type.",
"authors": [
"wneumann"
"wneumann",
"meatball133"
],
"contributors": []
}
121 changes: 72 additions & 49 deletions concepts/tuples/about.md
Original file line number Diff line number Diff line change
@@ -1,86 +1,109 @@
# About

[Tuples][tuples] are used to combine multiple values into a single compound value where each of the values may have a different type. The compound value has a type that is the combination of the individual values' types.
[Tuples][tuples] are used to combine multiple values into a single compound value where each of the values may have a different type.
The compound value has a type that is the combination of the individual values' types.
Like arrays, tuples are ordered collections.
However, contrary to arrays, tuples are fixed in size, thereby to change the number of elements in a tuple, a new tuple must be created.

To create a tuple, you enclose the values in parentheses, separated by commas:

```swift
let order: (String, Double, Int) = ("biscuits", 2.99, 3)
let order = ("biscuits", 2.99, 3)
```

The fact that tuples are single values allows them to be used to [return multiple values from a function][multiple-return-values]:
You can also specify the type of each value in the tuple:

```swift
func longestAndShortest(_ strings: [String]) -> (longest: String?, shortest: String?) {
var longestLength = Int.min, shortestLength = Int.max
var longAndShort: (longest: String?, shortest: String?) = (longest: nil, shortest: nil)
for string in strings {
if string.count > longestLength {
longAndShort.longest = string
longestLength = string.count
}
if string.count < shortestLength {
longAndShort.shortest = string
shortestLength = string.count
}
}
return longAndShort
}

longestAndShortest(["robin", "blue jay", "heron", "swift", "swan"])
// => (longest: "blue jay", shortest: "swan")
let order: (String, Double, Int) = ("biscuits", 2.99, 3)
```

The individual items of a tuple may be accessed by appending a `.n` to the tuple's name where _n_ is the index of the element you would like to access, starting with 0.
To extract the individual values from a tuple, you can use the `.n` syntax, where _n_ is the index of the element you would like to access, starting with 0:

```swift
let orderItem = order.0
// => "biscuits"
// Returns "biscuits"

let orderQuantity = order.2
// => 3
// Returns 3
```

## Named tuples

Tuples can be named by providing labels for each of the values:

```swift
let order = (item: "biscuits", price: 2.99, quantity: 3)
```

This can be useful for making the tuple more readable and self-explanatory, especially when the tuple is used as a return value from a function.

It also allows you to access the individual values by their names:

```swift
let orderItem = order.item
// Returns "biscuits"
let orderQuantity = order.quantity
// Returns 3
```

The components of a tuple may also be accessed through _decomposition_:
Same as non-named tuples, you can specify the type of each value in a named tuple:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Same as non-named tuples, you can specify the type of each value in a named tuple:
As with non-named tuples, you can specify the type of each value in a named tuple:


```swift
let (teamName, wins, losses, draws) = ("Loons", 15, 11, 8)
let points = 3 * wins + draws
// => 53
let order: (item: String, price: Double, quantity: Int) = (item: "biscuits", price: 2.99, quantity: 3)
```

Unneeded values can be ignored in decomposition by using an `_` in place of a name:
## Modifying tuples

Elements of a tuple can be modified, it can be done using the `.n` syntax.

```swift
let (_, wins, _, draws) = ("Loons", 15, 11, 8)
let points = 3 * wins + draws
// => 53
var order = ("biscuits", 2.99, 3)
order.0 = "cookies"
order.1 = 1.99
order.2 = 5

order
// Returns ("cookies", 1.99, 5)
```

You can provide more semantic information about a tuple by supplying labels to the components of a tuple. The individual elements can then be accessed by either their index or their label:
## Multiple return values

Functions in Swift can only return a single value.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are tuples a single value or a single object (containing multiple values)?

However, since a tuple is a single value, you can package multiple values into a tuple and return that tuple from a function.
This allows you to effectively [return multiple values from a function][multiple-return-values].

Here is an example of a function that returns a tuple with a quotient and a remainder:

```swift
let cindy: (name: String, age: Int) = (name: "Cindy", 28)
let cindyName = cindy.name
// => "Cindy"
let cindyAge = cindy.1
// => 28
func divide(_ dividend: Int, by divisor: Int) -> (quotient: Int, remainder: Int) {
let quotient = dividend / divisor
let remainder = dividend % divisor
return (quotient, remainder)
}
```

When tuples are given labels, the values may be assigned in a differeent order, so long as the labels are present and the types match. And the labels may be omitted so long as the type and order are correct:
## Tuple decomposition

You can decompose a tuple into its individual components by providing a number of variables equal to the number of elements in the tuple.
Using tuple decomposition can increase the readability of your code, since it allows you to assign meaningful names to the individual values.

```swift
let bob: (name: String, age: Int) = (age: 23, name: "Bob")
let jenny: (name: String, age: Int) = ("Jenny", 32)
let order = ("biscuits", 2.99, 3)
let (item, price, quantity) = order

item
// Returns "biscuits"
```

If the tuple is defined as a variable, the individual components can be updated by assigning new values to their labels or indices.
Decomposition can also be done with for-in loops:

```swift
var birdSightingLog = (week: 28, birds: ["robin", "blue jay", "heron"])
birdSightingLog.0 = 29
// => (week 29, ["robin", "blue jay", "heron"])
birdSightingLog.birds.append("swift")
// => (week 29, ["robin", "blue jay", "heron", "swift"])
let orders = [("biscuits", 2.99, 3), ("cookies", 1.99, 5)]

for (item, price, quantity) in orders {
print("Item: \(item), Price: \(price), Quantity: \(quantity)")
}
```

[tuples]: https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID329
[multiple-return-values]: https://docs.swift.org/swift-book/LanguageGuide/Functions.html#ID164
[tuples]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/thebasics/#Tuples
[multiple-return-values]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/functions/#Functions-with-Multiple-Return-Values
105 changes: 86 additions & 19 deletions concepts/tuples/introduction.md
Original file line number Diff line number Diff line change
@@ -1,42 +1,109 @@
# Introduction
# About

Tuples are used to combine multiple values into a single compound value where each of the values may have a different type. The compound value has a type that is the combination of the individual values' types.
[Tuples][tuples] are used to combine multiple values into a single compound value where each of the values may have a different type.
The compound value has a type that is the combination of the individual values' types.
Like arrays, tuples are ordered collections.
However, contrary to arrays, tuples are fixed in size, thereby to change the number of elements in a tuple, a new tuple must be created.

To create a tuple, you enclose the values in parentheses, separated by commas:

```swift
let order = ("biscuits", 2.99, 3)
```

You can also specify the type of each value in the tuple:

```swift
let order: (String, Double, Int) = ("biscuits", 2.99, 3)
```

The individual items of a tuple may be accessed by appending a `.n` to the tuple's name where _n_ is the index of the element you would like to access, starting with 0.
To extract the individual values from a tuple, you can use the `.n` syntax, where _n_ is the index of the element you would like to access, starting with 0:

```swift
let orderItem = order.0
// => "biscuits"
// Returns "biscuits"

let orderQuantity = order.2
// => 3
// Returns 3
```

## Named tuples

Tuples can be named by providing labels for each of the values:

```swift
let order = (item: "biscuits", price: 2.99, quantity: 3)
```

This can be useful for making the tuple more readable and self-explanatory, especially when the tuple is used as a return value from a function.

It also allows you to access the individual values by their names:

```swift
let orderItem = order.item
// Returns "biscuits"
let orderQuantity = order.quantity
// Returns 3
```

The components of a tuple may also be accessed through _decomposition_:
Same as non-named tuples, you can specify the type of each value in a named tuple:

```swift
let (teamName, wins, losses, draws) = ("Loons", 15, 11, 8)
let points = 3 * wins + draws
// => 53
let order: (item: String, price: Double, quantity: Int) = (item: "biscuits", price: 2.99, quantity: 3)
```

Unneeded values can be ignored in decomposition by using an `_` in place of a name:
## Modifying tuples

Elements of a tuple can be modified, it can be done using the `.n` syntax.

```swift
var order = ("biscuits", 2.99, 3)
order.0 = "cookies"
order.1 = 1.99
order.2 = 5

order
// Returns ("cookies", 1.99, 5)
```

## Multiple return values

Functions in Swift can only return a single value.
However, since a tuple is a single value, you can package multiple values into a tuple and return that tuple from a function.
This allows you to effectively [return multiple values from a function][multiple-return-values].

Here is an example of a function that returns a tuple with a quotient and a remainder:

```swift
let (_, wins, _, draws) = ("Loons", 15, 11, 8)
let points = 3 * wins + draws
// => 53
func divide(_ dividend: Int, by divisor: Int) -> (quotient: Int, remainder: Int) {
let quotient = dividend / divisor
let remainder = dividend % divisor
return (quotient, remainder)
}
```

You can provide more semantic information about a tuple by supplying labels to the components of a tuple. The individual elements can then be accessed by either their index or their label:
## Tuple decomposition

You can decompose a tuple into its individual components by providing a number of variables equal to the number of elements in the tuple.
Using tuple decomposition can increase the readability of your code, since it allows you to assign meaningful names to the individual values.

```swift
let order = ("biscuits", 2.99, 3)
let (item, price, quantity) = order

item
// Returns "biscuits"
```

Decomposition can also be done with for-in loops:

```swift
let cindy: (name: String, age: Int) = (name: "Cindy", 28)
let cindyName = cindy.name
// => "Cindy"
let cindyAge = cindy.1
// => 28
let orders = [("biscuits", 2.99, 3), ("cookies", 1.99, 5)]

for (item, price, quantity) in orders {
print("Item: \(item), Price: \(price), Quantity: \(quantity)")
}
```

[tuples]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/thebasics/#Tuples
[multiple-return-values]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/functions/#Functions-with-Multiple-Return-Values
11 changes: 10 additions & 1 deletion concepts/tuples/links.json
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
[]
[
{
"url": "https://docs.swift.org/swift-book/documentation/the-swift-programming-language/thebasics/#Tuples",
"description": "Swift Book: Tuples"
},
{
"url": "https://docs.swift.org/swift-book/documentation/the-swift-programming-language/functions/#Functions-with-Multiple-Return-Values",
"description": "Swift Book: Functions-with-Multiple-Return-Values"
}
]
24 changes: 18 additions & 6 deletions exercises/concept/santas-helper/.docs/hints.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,25 @@

- The individual components of a tuple can be accessed by appending a _.n_ to the name of the tuple, where _n_ is the index of the component, starting with 0.

## 1. Convert coordinates to polar
## 1. Get name of the toy

- The individual components of a labeled tuple can also be accessed by appending a _.label_ to the name of the tuple, where _label_ is the label name of the component.
- You can access the name of the toy by using the `.n` syntax.

## 2. Merge two database records
## 2. Add a new toy to the database

- Tuples can be [decomposed and assigned to individual constants or variables][tuples].
- If only some of the tuple's values are needed, unwanted components can be ignored by using an underscore (`_`) for the variable name when you decompose the tuple.
- You can create a new tuple by using the syntax tuple `(name1: value1, name2: value2, ...)`.

[tuples]: https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID329
## 3. Update quantity of a toy

- You can use a [for-loop][for-loop] to iterate over the array of tuples and update the quantity of the toy.
- You can use earlier implemented functions to get the name of the toy.
- You can use a [conditional statement][conditional-statement] to check if the name of the toy matches the one you want to update.
- You can use the `.n` syntax to update the quantity of the toy, e.g: `toys.price = 3`.

## 4. Add category key to a toy

- You can use a [for-loop][for-loop] to iterate over the array of tuples and add the category key to the toy.
- A tuple is immutable, so you need to create a new tuple with the category key added.

[for-loop]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/controlflow/#For-In-Loops
[conditional-statement]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/controlflow/#Conditional-Statements
Loading