-3

I want to sort an array

like this:

let elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]

I tried do this

var currentElement = ""
var newElements:[String] = []
for element in elements {
    if currentElement != element{
        currentElement = element
        newElements.append(element)
    }
}

but print["S", "A", "C", "T", "E", "F", "S", "A", "C"]

How to sort this to ["A","C","E","F","S","T"]

Kenny
  • 39
  • 1
  • 5
  • 1
    Wtf, you are not even sorting anything in your if condition, it's not even AN ATTEMPT to sort anything, you are just suppressing the duplicates ! Looks to me a lot like some kind of homework you don't want to do, get back to work and search on google. – N.K Jun 06 '18 at 08:21
  • 1
    First: Unique values: https://stackoverflow.com/questions/27624331/unique-values-of-array-in-swift Then sort: https://stackoverflow.com/questions/26719744/swift-sort-array-of-objects-alphabetically – Larme Jun 06 '18 at 08:22

3 Answers3

5
let elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]

let sortedElements = elements.sorted(by: {$0 < $1})

print(sortedElements)

prints:

["A", "A", "A", "C", "C", "C", "E", "E", "E", "F", "S", "S", "S", "T"]
Teetz
  • 3,475
  • 3
  • 21
  • 34
3

What you want to do is to remove the duplicates and then sort it, right?

You can convert it to a Set, and then call sorted():

let elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]
let newElements = Set(elements).sorted() // ["A", "C", "E", "F", "S", "T"]
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

You should use ComparisonResult to sort your array alphabetical, because Set(elements).sorted() and you have lowercase characters, the result of sort will be wrong.

var elements = ["S","A","C","C","T","E","E","E","F","S","S","A","A","C"]

elements = elements.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }

//the output["A", "A", "A", "C", "C", "C", "E", "E", "E", "F", "S", "S", "S", "T"]
A.Munzer
  • 1,890
  • 1
  • 16
  • 27