0

I have a String array

let myArray = ["b", "a", "*", "c", "5"]

I want tot sort it. After the sort, sorted letters should be first and symbols and number should follow.

let sortedArray = myArray.sorted { $0 < $1 }
print(sortedArray) 
//I get ["*", "5", "a", "b", "c"]
//I want ["a", "b", "c", "5", "*"]

EDIT: I saw this Answer. Is there any short/better way?

iOSDev
  • 326
  • 2
  • 10

1 Answers1

1

There is a better way, I wrote this function, much shorter than the one you linked. Hope you enjoy it! :)

func sortCharacters(array : [String]) -> [String] {
    let letters = array.joined().filter {$0.isLetter}.sorted()
    let numbers = array.joined().filter {$0.isNumber}.sorted()
    let symbols = array.joined().filter {!$0.isLetter && !$0.isNumber}.sorted()
    return Array(letters + numbers + symbols).map {String($0)}
}

let chars = ["*", "5", "a", "b", "c"]
print(sortCharacters(array: chars)) //["a", "b", "c", "5", "*"]
Talon Brown
  • 127
  • 13