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

前端 未结 3 967
忘掉有多难
忘掉有多难 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:22

    The key is to write your "is ordered before" function to do whatever you want. For example, if by digits, you mean "0"..."9", then something like this is probably what you want:

    func isDigit(c: Character) -> Bool {
        return "0" <= c && c <= "9"
    }
    
    func sortedLettersFirst(lhs: String, rhs: String) -> Bool {
        for (lc, rc) in zip(lhs.characters, rhs.characters) {
            if lc == rc { continue }
    
            if isDigit(lc) && !isDigit(rc) {
                return false
            }
            if !isDigit(lc) && isDigit(rc) {
                return true
            }
            return lc < rc
        }
        return lhs.characters.count < rhs.characters.count
    }
    
    words.sort(sortedLettersFirst)
    

    Of course, if by "digit" you mean "unicode digits", then see What is the replacement for isDigit() for characters in Swift? for a different approach to isDigit. But ultimately, the point is to make whatever rule you want in your isOrderedBefore function, and pass that to sort().

提交回复
热议问题