UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 3: reversed arrays

Forums > 100 Days of SwiftUI

Hello community,

I'm new here and I'm glad for having initiated this course and grateful for Paul making it available for free. I've encountered a problem with the .reversed() function on arrays, which is that I don't know how to actually use them. Even if they are not really arrays anymore, I expected to be able to access any index of them as if they were. Otherwise, what's the point?

Thanks!

Lucas

2      

Can you show some code that illustrates your confusion? What is it you are expecting to be able to do that you can't do?

2      

Maybe these articles will help.

Reverse sort an array

Loop though an array in reverse

.reversed() gives you a ReversedCollection of Element based on the original. In my example below, element type is a String.

To create a new item with reversed elements you actually need to specify the element type - which is how fruitsReversed is declared. Notice how fruitsReversed and fruitsReversedCollection are not the same type.

Try the code in the Playground

var fruits = ["apples", "pears", "oranges", "plums"]
var fruitsReversed: [String] = fruits.reversed()
let fruitsReversedCollection = fruits.reversed()

print(fruits)
print(fruitsReversed)
print(fruits[2])
print(fruitsReversed[2])
print("Second item in fruits - ",fruits[1], "- is the same as third item in fruitsReversed -", fruitsReversed[2])
print(fruitsReversedCollection)
print("")

fruits.append("banana")    // add 'banana' to the fruits

print("The fruits array has changed: ",fruits)
print("No change to the fruitsReversed array: ", fruitsReversed)
print(fruits[2])
print(fruitsReversed[2])
print("Second item in fruits - ", fruits[1], "- is still the same as third item in fruitsReversed -", fruitsReversed[2])
print(fruitsReversedCollection)
print("")

print("fruitsReversed still has no banana:", fruitsReversed)

fruitsReversed = fruits.reversed()  // update fruitsrReversed

print("fruitsReversed now with added banana:", fruitsReversed)
print("Second item in fruits -", fruits[1], "- is no longer same as third item in fruitsReversed -", fruitsReversed[2])

2      

Thank you for your answers, these were helpful.

At least now I know that with type annotation [String] I can create an array and these two arrays are of the same type, thus they behave equally.

The thing that was causing confusion to me was this:

In the fruitsReversedCollection I couldn't use indexes to access the reversed items, so I don't get the usefulness of the reversed collection. Paul says that swift is very clever, so it stores the collection as a reverse of a base collection, but I don't know how to use this collection.

ReversedCollection<Array<String>>(_base: ["apples", "pears", "oranges", "plums"])

2      

Using .reversed without allocation storage, means that you save memory if all you want to do is to refer to the original array but in reverse order.

Being a ReversedCollection means that it conforms to the Collection protocol, and all the methods and functions that are applicable and available to Collections, are also available to a ReversedCollection.

Apple Documentation for ReversedCollection

You can also see the same documentation in Xcode.

Try adding the following code to the end of the previous code in the Playground. The results using .forEach and for x in are the same, as are the results for .map and .compactMap.

print("")
fruitsReversedCollection.forEach { afruit in
    print(afruit)
}

print("")
for bfruit in fruitsReversedCollection {
    print(bfruit)
}

print("")
print(fruitsReversedCollection.first!)
print(fruitsReversedCollection.startIndex)
print(fruitsReversedCollection.endIndex)
print(fruitsReversedCollection.first(where: { $0.count > 5} ) ?? "")
print(fruitsReversedCollection.compactMap( {$0.count > 5} ))
print(fruitsReversedCollection.map( {$0.count > 5} ))
print(fruitsReversedCollection.filter( {$0.count > 5 } ))

let newReversedArray = fruitsReversedCollection.filter( {$0.count > 5 } )

print("")
print(newReversedArray)

Until the newReversedArray was created, no additional storage was allocated. .filter returns an actual array.

Strictly speaking, this also allocates memory, but it is released as soon as the print function is completed.

print(fruitsReversedCollection.filter( {$0.count > 5 } )

2      

I think I know how to answer Lucas's question

The code that Paul typed only want to show this message: ReversedCollection<Array<String>>(_base: ["Bush", "Obama", "Trump", "Biden"]) in english: this is the reversed collection of string array that take from the base of "Bush" "Obama" "Trump" "Biden"

there is nothing useful about this because he only wanted to show you that message, how clever swift is.

He wanted to show that using reversed() can save a lot time and memory. Instead of you creating new array that going to take more memory, the new reversed array will take the original array and remember them and reverse them internally.

hope I don't disappoint you with my broken English answer.

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.