The array value should be sort like (alphabetic, numbers and special characters)

前端 未结 3 549
萌比男神i
萌比男神i 2021-01-21 23:48

I tried to sort like the array as follows:

let students: Set = [\"23412334\",\"&234@fwv\",\"Kofi\", \"Abena\", \"Peter\", \"Kweku\", \"Akosua\"]
let sortedSt         


        
3条回答
  •  耶瑟儿~
    2021-01-22 00:39

    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 = Set(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"])
            static let lowestPriority: Set = 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.

提交回复
热议问题