使用空项目在Swift Ascending中对数组进行排序

B_s*_*B_s 4 arrays sorting xcode alphabetical swift

在Xcode(Swift)中,我有一个初始化为100个空项的数组:

var persons = [String](count:100, repeatedValue: "")
Run Code Online (Sandbox Code Playgroud)

通过一些函数,我将内容添加到数组中的位置,从0开始.

所以例如我的数组在某个特定时刻:

["Bert", "Daniel", "Claire", "Aaron", "", "", ... ""]
Run Code Online (Sandbox Code Playgroud)

用点表示其余的空项目.我使用此函数按字母顺序对数组进行排序:

persons = persons.sorted {$0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
Run Code Online (Sandbox Code Playgroud)

这给了我一个像这样的数组:

["", "", ... , "Aaron", "Bert", "Claire", "Daniel"]
Run Code Online (Sandbox Code Playgroud)

我想要的是按字母顺序排序我的数组,而不是前面的空项目.我需要得到一个像:

["Aaron", "Bert", "Claire", "Daniel", "", "", ... , ""]
Run Code Online (Sandbox Code Playgroud)

就我而言,我不想要一个带有空项的数组但是我发现如果我没有声明像100个项目那么我就无法为我的数组添加一个值(该数组不会被填充到100个项目中,这是为了当然).

谁能帮我吗?

Mik*_*e S 6

正如@Antonio所说,看起来你需要一个降序的字符串.除了Dictionary@Antonio的答案中的方法(效果很好),你也可以使用NSMutableSet(从Objective-C桥接):

let personSet = NSMutableSet()
personSet.addObject("Aaron")
personSet.addObject("Daniel")
personSet.addObject("Claire")
personSet.addObject("Aaron")
personSet.addObject("Bert")
personSet.addObject("Bert")
personSet.addObject("Joe")
personSet.removeObject("Joe") // You can remove too of course
Run Code Online (Sandbox Code Playgroud)

这创建了集合:

{(
    Claire,
    Aaron,
    Daniel,
    Bert
)}
Run Code Online (Sandbox Code Playgroud)

然后,当你想要人们作为一个Array,你可以使用allObjects演员来[String]:

personSet.allObjects as [String]
Run Code Online (Sandbox Code Playgroud)

你可以像你现在一样对它进行排序:

let people = (personSet.allObjects as [String]).sort {$0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
Run Code Online (Sandbox Code Playgroud)

这使得people:

[Aaron, Bert, Claire, Daniel]
Run Code Online (Sandbox Code Playgroud)

对于那些想知道如何对Array问题中最初陈述的内容进行排序的人(升序但最后是空字符串),可以使用sort函数中的一些自定义逻辑来完成:

var persons = ["Bert", "Daniel", "Claire", "Aaron", "", "", ""]
persons.sort { (a, b) -> Bool in
    if a.isEmpty {
        return false
    } else if b.isEmpty {
        return true
    } else {
        return a.localizedCaseInsensitiveCompare(b) == .OrderedAscending
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

["Aaron", "Bert", "Claire", "Daniel", "", "", ""]
Run Code Online (Sandbox Code Playgroud)