Home > Enterprise >  Sorting Array of String with Multiple Languages
Sorting Array of String with Multiple Languages

Time:08-10

I want to sort an array in certain order, starting with English words then Arabic words finally any words that start with numbers or special characters [English, Arabic , numbers and special characters]

Example:

input ["1234", "أحمد", "Jack", "Sarah"]

Expected result:

[
    "Jack",
    "Sarah",
    "أحمد",
    "1234",
]

Expected result

CodePudding user response:

Use sorted(by:) to define you own comparison code.

In your case, I suggest defining an enum with categories:

enum StringSortCategory: Int {
    case english
    case nonEnglish
    case nonLetter
}

extension String {
    var category: StringSortCategory {
        guard let firstChar = first else { return .nonLetter }
        if firstChar.isLetter {
            return firstChar.isASCII ? .english : .nonEnglish
        }
        return .nonLetter
    }
}

Then you can sort using code like this:

let output = input.sorted { a, b in
    let categoryA = a.category
    let categoryB = b.category
    if categoryA == categoryB {
        return a < b
    }
    return categoryA.rawValue < categoryB.rawValue
}
  • Related