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

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

    How about this.

    func sortedNumbersLast(words: [String]) -> [String] {
      var startsWithDigit     = [String]()
      var startsWithCharacter = [String]()
    
      for word in words {
        if let first = word.characters.first {
          if first >= "0" && first <= "9" {
            startsWithDigit.append(word)
          }
          else {
            startsWithCharacter.append(word)
          }
        }
      }
      return startsWithCharacter.sort(<) + startsWithDigit.sort(<)
    }
    

提交回复
热议问题