In Swift, how do I sort an array of strings and have strings of numbers, symbols, etc. always come after alphabetic strings?

前端 未结 3 918
忘掉有多难
忘掉有多难 2021-01-22 21:58

I want to sort an array of strings so that alphabetic characters are always before any other kinds of characters. For example:

[\"800\", \"word\", \"test\"]
         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-22 22:29

    Try this in Playground, as you can see in the console output it gets the job done, letters are being placed at the front, followed by numbers and other symbols are at the end.

       let stringsSortedByLettersFirstNumbersThenAndOtherSymbolsAtTheEnd: (String, String) -> Bool = { s1, s2 -> Bool in
            guard let f1 = s1.first, let f2 = s2.first else {
                return s1 < s2
            }
            if f1.isLetter == false && f2.isLetter {
                return false
            }
            if f1.isLetter && f2.isLetter == false {
                return true
            }
            if f1.isNumber == false && f2.isNumber {
                return false
            }
            if f1.isNumber && f2.isNumber == false {
                return true
            }
            return s1 < s2
        }
    
        let str = ["4", "A", "B", "Z", "T", "3", "'", "8"]
    
        print(str.sorted(by: stringsSortedByLettersFirstNumbersThenAndOtherSymbolsAtTheEnd))
    

    Above method sorts String in ascending order, if you want to do the other way just change the lines

            return s1 < s2
    

    to

            return s1 > s2
    

提交回复
热议问题