-
-
Notifications
You must be signed in to change notification settings - Fork 159
[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
meatball133
wants to merge
1
commit into
main
Choose a base branch
from
update-tuple
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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": [] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: | ||
|
||
```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. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.