I tried to sort like the array as follows:
let students: Set = [\"23412334\",\"&234@fwv\",\"Kofi\", \"Abena\", \"Peter\", \"Kweku\", \"Akosua\"]
let sortedSt
let words = ["23412334","&234@fwv","Kofi", "Abena", "Peter", "Kweku", "Akosua"]
func sortedNumbersLast(words: [String]) -> [String] {
var startsWithDigit = [String]()
var startsWithCharacter = [String]()
var startsWithSymbol = [String]()
for word in words {
if let first = word.characters.first {
if first >= "0" && first <= "9" {
startsWithDigit.append(word)
}
else {
if(!(first >= "a" && first <= "z") && !(first >= "A" && first <= "Z") ){
startsWithSymbol.append(word)
}else{
startsWithCharacter.append(word)
}
}
}
}
return startsWithCharacter.sorted(by: <) + startsWithDigit.sorted(by: <) + startsWithSymbol.sorted()
}
print(sortedNumbersLast(words: words))
["Abena", "Akosua", "Kofi", "Kweku", "Peter", "23412334", "&234@fwv"]
Modified Answer
Follow these steps
First sort the array as you have sorted.
Remove the strings starting with special characters and save it in another array.
The "correct" way to do it is to define your own sort comparator and use sorted(by:)
which sorts using your comparator. In the example below, I define a "priority" based on the category of the first character in the string, and then a two level sort based first on priority and then on the normal string ordering
extension String
{
enum Priority
{
case normal
case low
case lowest
static let lowPriority: Set<Character> = Set(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"])
static let lowestPriority: Set<Character> = Set(["&"])
static func < (a: Priority, b: Priority) -> Bool
{
switch (a, b)
{
case (.normal, .low), (.normal, .lowest), (.low, .lowest):
return true
default:
return false
}
}
}
var priority: Priority
{
let first = self.characters.first! // fatal error for empty strings
if Priority.lowestPriority.contains(first)
{
return .lowest
}
else if Priority.lowPriority.contains(first)
{
return .low
}
return .normal
}
}
let students: Set = ["23412334","&234@fwv","Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted {
(a, b) -> Bool in
if a.priority < b.priority
{
return true
}
else if b.priority < a.priority
{
return false
}
return a < b
}
print(sortedStudents)
There may be bugs still, but it works for your test case.