Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

No exact matches in call to subscript, reversed array in Swift

I am trying to understand different Swift’s basics better. I bumped on the reversed array concept in Paul Hudson’s videos.

He said that the array will be printed in the same order as the original one, but also that other operations will be done on the reversed version of the array.

And so I did this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let presidents = ["Bush", "Obama", "Trump", "Biden"]
let reversedPresidents = presidents.reversed()

print(reversedPresidents[2])

And I received:

No exact matches in call to subscript 

error.

Why?

>Solution :

It’s explained reversed documentation.

First of all, it returns the type ReversedCollection<Array<Element>>

Secondly, it doesn’t really change the order of array, as explained here:

or ordinary collections c having bidirectional indices:

  • c.reversed() does not create new storage
  • c.reversed().map(f) maps eagerly and returns a new array

In other words: reversed() is able to iterate the provided array in reverse order, but does not create a reversed array

So if you want to create a reversed array, you can either do this:

let reversedPresidents = presidents.reversed().map { $0 }

or, as mentioned in comment above,

let reversedPresidents = Array(presidents.reversed())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading