Home > Software design >  No exact matches in call to subscript, reversed array in Swift
No exact matches in call to subscript, reversed array in Swift

Time:01-12

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:

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?

CodePudding user response:

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())
  •  Tags:  
  • Related