Created
December 9, 2022 10:02
-
-
Save yannxou/66d81264e3b61ea3e9ad4117ea57dbbe to your computer and use it in GitHub Desktop.
Swift Array appending (the functional way)
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
| public extension Array { | |
| /// Adds the elements of a sequence to the end of the array and returns a copy of it. | |
| /// | |
| /// This example creates a new array containing the elements of a | |
| /// `Range<Int>` instance added to an array of integers | |
| /// | |
| /// let array = [1, 2, 3, 4, 5] | |
| /// let numbers = array.appending(contentsOf: 10...15) | |
| /// print(numbers) | |
| /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" | |
| /// | |
| /// - Parameter newElements: The elements to append to the array. | |
| /// - Returns: The new array containing every element | |
| func appending<S>(contentsOf newElements: S) -> Array where Element == S.Element, S: Sequence { | |
| var copy = self | |
| copy.append(contentsOf: newElements) | |
| return copy | |
| } | |
| /// Adds the given element to the end of the array and returns a copy of it. | |
| /// | |
| /// This example creates a new array containing the new element | |
| /// | |
| /// let array = [1, 2, 3, 4, 5] | |
| /// let numbers = array.appending(6) | |
| /// print(numbers) | |
| /// // Prints "[1, 2, 3, 4, 5, 6]" | |
| /// | |
| /// - Parameter newElement: The element to append to the array. | |
| /// - Returns: The new array containing the new element | |
| func appending(_ newElement: Self.Element) -> Array { | |
| var copy = self | |
| copy.append(newElement) | |
| return copy | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment