arrays - Why does the reverse() function in the Swift standard library return ReverseRandomAccessCollection? -


now i've learned swift (to reasonable level) i'm trying grips standard library, in truth it's ελληνικά me!

so specific question: have array of strings , can call reverse() on it.

let arr = ["mykonos", "rhodes", "naxos"].reverse() 

now naively thought i'd type of array this. (ruby example has similar method pass array , array)

but arr of type

reverserandomaccesscollection<array<string>> 

which struct, conforms collectiontype:

public struct reverserandomaccesscollection<base : collectiontype base.index : randomaccessindextype> : _reversecollectiontype 

this means can this:

for item in arr {   print(item) } 

but can't do

print(arr[0]) 

why designed way?

dictionaries in swift implement collectiontype, can this:

let dict = ["greek" : "swift sometimes", "notgreek" : "ruby example"].reverse() 

but dictionaries not ordered arrays, why can call reverse() on dicts?

bonus points if can point me in direction of can read , improve swift stdlib foo, Ευχαριστώ!

it performance optimization both time , memory. reverserandomaccesscollection presents elements of original array in reverse order, without need create new array , copying elements (as long original array not mutated).

you can access reversed elements subscripts:

let el0 = arr[arr.startindex] let el2 = arr[arr.startindex.advancedby(2)] 

or

for in arr.indices {     print(arr[i]) } 

you can create array explicitly with

let reversed = array(["mykonos", "rhodes", "naxos"].reversed()) 

a dictionary sequence of key/value pairs. in

let dict = ["greek" : "swift sometimes", "notgreek" : "ruby example"].reverse() 

a different reversed() method called:

extension sequencetype {     /// return `array` containing elements of `self` in reverse     /// order.     ///     /// complexity: o(n), n length of `self`.     @warn_unused_result     public func reversed() -> [self.generator.element] } 

the result array key/value pairs of dictionary in reverse order. of limited use because order of key/value pairs in dictionary can arbitrary.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -