Search code examples
swiftset

No last property for "set" any more?


The book I've read claims that "You can use the first and last properties, which return one of the elements in the set".

However, I've tried it and seems it is not working. I would very appreciate if someone can explain it for me.

enter image description here


Solution

  • You cannot ask for the last item of a Set. Indeed, a Set is not ordered, so there is not last item (nor last property).

    Don't hesitate to take a look at the Swift Doc on Set.

    If you want to find the last element, you need an ordered collection like an Array:

    var myArray = [1, 2, 3, 4, 5]
    print(myArray.last) // Display 5