Reading Apple's Swift guide, more specifically the Closures chapter I've stumbled upon a problem. A String array is declared
var names = ["Cris", "Alex", "Ewa", "Barry", "Daniella"]
The purpose of this section is to pass an array of Strings (the one above) and with the function sort(_:) have the same array back but sorted using an auxiliary method by providing a closure. The closure is the method backwards
func backwards(s1: String, s2: String) -> Bool {
return s1 > s2
}
Then an array, reversed, is declared and applied the method sort to the original array, names:
var reversed = names.sort(backwards)
AFAIK reversed should be inferred as an array of Strings but when I check it is inferred as var reversed: <>. Now, reversed doesn't store anything and an error pops up:
Immutable value of type '[String]' only has mutating members named 'sort'
Later on in the chapter the closure is simplified a lot but I get the same error as now so I tried to fix it when the expression is simple enough but I have no clue on what to do.
I don't know if the book forgot something or is my mistake, help will be appreciated. Thank you in advance!
sortdoesn't create a new sorted array, but mutates the original one, which in this case cannot be mutated since you decleared it as a constant with theletkeyword.sortdoesn't return anything. If you want to store the sorted array in the variablereversed, you should just do:names.sort(backwards)thenvar reversed = names, but in this casenamesandreversedwill contain the same elements.sortmethod of array andsortedglobal method. Please checkout book again