1

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!

6
  • 1
    sort doesn'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 the let keyword. Commented Aug 6, 2015 at 9:27
  • Done that, now names is a variable. But when I declare var reversed a warning pops up saying Variable 'reversed' inferred to have type '()', which may be unexpected. Commented Aug 6, 2015 at 9:29
  • 2
    yes, because, sort doesn't return anything. If you want to store the sorted array in the variable reversed, you should just do: names.sort(backwards) then var reversed = names, but in this case names and reversed will contain the same elements. Commented Aug 6, 2015 at 9:34
  • hmm, now it works. What I don't know is why in the book does it like the code above and it works. Thank you! Commented Aug 6, 2015 at 9:39
  • Dude theres a difference between sort method of array and sorted global method. Please checkout book again Commented Aug 6, 2015 at 10:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.