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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26566860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:00:08  来源:igfitidea点击:

Sort array in Swift Ascending with empty items

arraysxcodesortingswiftalphabetical

提问by B_s

In Xcode (Swift) I have an array that is initialized to 100 empty items:

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

var persons = [String](count:100, repeatedValue: "")

With some functions I add content to the places in the array, starting at 0.

使用一些函数,我将内容添加到数组中的位置,从 0 开始。

So for example my array is at some given moment:

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

["Bert", "Daniel", "Claire", "Aaron", "", "", ... ""]

With the dots representing the rest of the empty items. I use this function for sorting my array alphabetically:

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

persons = persons.sorted {
["", "", ... , "Aaron", "Bert", "Claire", "Daniel"]
.localizedCaseInsensitiveCompare() == NSComparisonResult.OrderedAscending }

This gives me an array back like this:

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

["Aaron", "Bert", "Claire", "Daniel", "", "", ... , ""]

What I want is to sort my array alphabetically but not with the empty items at the front. I need to get an array back like:

我想要的是按字母顺序对我的数组进行排序,而不是前面的空项。我需要取回一个数组,如:

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

For my part, I do not want an array with empty items but I found I couldn't add a value to my array if I did not declare like a 100 items (the array won't be filled to a 100 items, that's for sure).

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

Can anyone help me out?

谁能帮我吗?

回答by Mike S

As @Antonio said, it looks like you need a descending order setof strings. Besides the Dictionarymethod in @Antonio's answer (which works great), you can also use NSMutableSet(bridged from Objective-C):

作为@Antonio说,它看起来像你需要一个降序串。除了Dictionary@Antonio 的答案中的方法(效果很好),您还可以使用NSMutableSet(从 Objective-C 桥接):

{(
    Claire,
    Aaron,
    Daniel,
    Bert
)}

Which creates the set:

创建集合:

personSet.allObjects as [String]

Then, when you want the people as an Array, you can use the allObjectscast to a [String]:

然后,当您希望人们成为 时Array,您可以使用allObjects强制转换为[String]

let people = (personSet.allObjects as [String]).sort {
[Aaron, Bert, Claire, Daniel]
.localizedCaseInsensitiveCompare() == NSComparisonResult.OrderedAscending }

And you can sort it just like you're currently doing:

您可以像当前一样对其进行排序:

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
    }
}

Which makes people:

这使得people

["Aaron", "Bert", "Claire", "Daniel", "", "", ""]


For those wondering how to sort the Arrayas originally stated in the question (Ascending but with empty strings at the end), that can be done with a little bit of custom logic in the sort function:

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

var persons = [String : Bool]()

persons["Bert"] = true
persons["Daniel"] = true
persons["Clair"] = true
persons["Clair"] = true
persons["Aaron"] = true
persons["Daniel"] = true
persons["Clair"] = true

Result:

结果:

var values = persons.keys.array

回答by Antonio

Reading comments in your question and other answers, I realize that you need a ordered set, containing unique values. There's no built in data structure in swift for that, but it can be easily be done by using a dictionary: simply use the string value as dictionary key, and a boolean as dictionary value - this ensures that keys are unique:

阅读您的问题和其他答案中的评论,我意识到您需要一个包含唯一值的有序集合。swift 中没有内置的数据结构,但可以通过使用字典轻松完成:只需使用字符串值作为字典键,并使用布尔值作为字典值 - 这确保键是唯一的:

values.sort { 
persons = persons
            .filter( { 
var persons = [String]()
var inputData = ["Bert", "Daniel", "Bert", "Claire", "Aaron"]
for item in inputData {
    var found = false
    for existing in persons {
        if existing == item {
            found = true
            break
        }
    }
    if (!found) {
         persons.append(item)
    }
}
persons.sort{##代码##.localizedCaseInsensitiveCompare() == NSComparisonResult.OrderedAscending }
println(persons)
.isEmpty == false } ) .sorted {##代码##.localizedCaseInsensitiveCompare() == NSComparisonResult.OrderedAscending }
.localizedCaseInsensitiveCompare() == NSComparisonResult.OrderedAscending }

You can quickly verify that with the above code the dictionary contains 4 elements only.

您可以使用上述代码快速验证字典仅包含 4 个元素。

Next, obtain a copy of the dictionary keys (as an array):

接下来,获取字典键的副本(作为数组):

##代码##

and sort it:

并排序:

##代码##

Alternatively, if you want to stick with the fixed sized array, you can remove the empty items before sorting:

或者,如果您想坚持使用固定大小的数组,您可以在排序之前删除空项目:

##代码##

回答by CuriousRabbit

I think you are confused about arrays. Swift arrays are not statically allocated structures which must be allocated and filled to maximum design capacity. Below is a crude example of how you can accomplish most of what you are expressing here. However, I really think that a dictionary is better suited to your needs.

我认为您对数组感到困惑。Swift 数组不是静态分配的结构,必须分配和填充到最大设计容量。下面是一个粗略的例子,说明如何完成你在这里表达的大部分内容。但是,我真的认为字典更适合您的需求。

##代码##