ios 按键的值对字典的 Swift 数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30446812/
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-08-31 06:04:26  来源:igfitidea点击:

Sort Swift Array of Dictionaries by Value of a Key

iosswift

提问by Hyman Amoratis

I am attempting to sort a Swift array which is composed of dictionaries. I have prepared a working example below. The goal is to sort the entire array by the "d" element in the dictionaries. I have prepared this working example which can be placed into a Swift project:

我正在尝试对由字典组成的 Swift 数组进行排序。我在下面准备了一个工作示例。目标是按字典中的“d”元素对整个数组进行排序。我准备了这个工作示例,可以将其放入 Swift 项目中:

var myArray = Array<AnyObject>()
var dict = Dictionary<String, AnyObject>()

dict["a"] = "hickory"
dict["b"] = "dickory"
dict["c"] = "dock"
dict["d"] = 5

myArray.append(dict)

dict["a"] = "three"
dict["b"] = "blind"
dict["c"] = "mice"
dict["d"] = 6

myArray.append(dict)

dict["a"] = "larry"
dict["b"] = "moe"
dict["c"] = "curly"
dict["d"] = 2

myArray.append(dict)

println(myArray[0])
println(myArray[1])
println(myArray[2])
}

This results in the following output to the log:

这会导致以下输出到日志:

{
    a = hickory;
    b = dickory;
    c = dock;
    d = 5;

}
{
    a = three;
    b = blind;
    c = mice;
    d = 6;
}
{
    a = larry;
    b = moe;
    c = curly;
    d = 2;
}

The goal is to sort the array by the "d" element, so that the above output would be changed to the following (which is based on numerical order of "d": '2, 5, 6'):

目标是按“d”元素对数组进行排序,以便将上述输出更改为以下内容(基于“d”的数字顺序:'2, 5, 6'):

{
    a = larry;
    b = moe;
    c = curly;
    d = 2;
}
{
    a = hickory;
    b = dickory;
    c = dock;
    d = 5;
}
{
    a = three;
    b = blind;
    c = mice;
    d = 6;
}

There are some other questions that seem similar, but when you look at them, it becomes clear they are not addressing this. Thank you for your assistance.

还有一些其他问题看起来很相似,但是当您查看它们时,很明显它们没有解决这个问题。谢谢您的帮助。

回答by oisdk

To declare, if you need to keep it as AnyObject, you have to explicitly cast:

要声明,如果您需要将其保留为 AnyObject,则必须显式转换:

var myArray = Array<AnyObject>()
var dict = Dictionary<String, AnyObject>()

dict["a"] = ("hickory" as! AnyObject)
dict["b"] = ("dickory" as! AnyObject)
dict["c"] = ("dock" as! AnyObject)
dict["d"] = (6 as! AnyObject)

myArray.append(dict as! AnyObject)

dict["a"] = ("three" as! AnyObject)
dict["b"] = ("blind" as! AnyObject)
dict["c"] = ("mice" as! AnyObject)
dict["d"] = (5 as! AnyObject)


myArray.append(dict as! AnyObject)

dict["a"] = ("larry" as! AnyObject)
dict["b"] = ("moe" as! AnyObject)
dict["c"] = ("curly" as! AnyObject)
dict["d"] = (4 as! AnyObject)

myArray.append(dict as! AnyObject)

Without appending, you can do it like this:

无需附加,您可以这样做:

var myArray: [AnyObject] = [ ([
    "a" : ("hickory" as! AnyObject),
    "b" : ("dickory" as! AnyObject),
    "c" : ("dock" as! AnyObject),
    "d" : (6 as! AnyObject)
  ] as! AnyObject), ([
    "a" : ("three" as! AnyObject),
    "b" : ("blind" as! AnyObject),
    "c" : ("mice" as! AnyObject),
    "d" : (5 as! AnyObject)
  ] as! AnyObject), ([
    "a" : ("larry" as! AnyObject),
    "b" : ("moe" as! AnyObject),
    "c" : ("curly" as! AnyObject),
    "d" : (4 as! AnyObject)
  ] as! AnyObject)
]

Which gives you the same result. Although, if only the value object in the dictionary needs to change, you don't need to cast the elements of the array:

这给你同样的结果。虽然,如果只需要更改字典中的值对象,则不需要强制转换数组的元素:

var myArray: [Dictionary<String, AnyObject>] = [[
    "a" : ("hickory" as! AnyObject),
    "b" : ("dickory" as! AnyObject),
    "c" : ("dock" as! AnyObject),
    "d" : (6 as! AnyObject)
  ], [
    "a" : ("three" as! AnyObject),
    "b" : ("blind" as! AnyObject),
    "c" : ("mice" as! AnyObject),
    "d" : (5 as! AnyObject)
  ], [
    "a" : ("larry" as! AnyObject),
    "b" : ("moe" as! AnyObject),
    "c" : ("curly" as! AnyObject),
    "d" : (4 as! AnyObject)
  ]
]

Then, to sort, you use the sort() closure, which sorts an Array in place. The closure you supply takes two arguments (named $0 and $1), and returns a Bool. The closure should return true if $0 is ordered before $1, or false if it comes after. To do this, you've got to cast an awful lot:

然后,为了排序,你使用 sort() 闭包,它对一个 Array 进行排序。您提供的闭包采用两个参数(名为 $0 和 $1),并返回一个 Bool。如果 $0 在 $1 之前排序,则闭包应该返回 true,如果在 $1 之后排序,则返回 false。要做到这一点,你必须投很多:

//myArray starts as: [
//  ["d": 6, "b": "dickory", "c": "dock", "a": "hickory"],
//  ["d": 5, "b": "blind", "c": "mice", "a": "three"],
//  ["d": 4, "b": "moe", "c": "curly", "a": "larry"]
//]

myArray.sort{
  ((
let sortedResults = (userArray as NSArray).sortedArray(using: [NSSortDescriptor(key: "name", ascending: true)]) as! [[String:AnyObject]]
as! Dictionary<String, AnyObject>)["d"] as? Int) < (( as! Dictionary<String, AnyObject>)["d"] as? Int) } //myArray is now: [ // ["d": 4, "b": "moe", "c": "curly", "a": "larry"], // ["d": 5, "b": "blind", "c": "mice", "a": "three"], // ["d": 6, "b": "dickory", "c": "dock", "a": "hickory"] //]

回答by Barath

Sort Array of Dictionary in Swift 3 & 4

在 Swift 3 & 4 中对字典数组进行排序

var array: [[String:Any]] = []
var dict: [String: Any] = [:]

dict["a"] = "hickory"
dict["b"] = "dickory"
dict["c"] = "dock"
dict["d"] = 5

array.append(dict)

dict["a"] = "three"
dict["b"] = "blind"
dict["c"] = "mice"
dict["d"] = 6

array.append(dict)

dict["a"] = "larry"
dict["b"] = "moe"
dict["c"] = "curly"
dict["d"] = 2

array.append(dict)

回答by Leo Dabus

edit/update: Xcode 11 ? Swift 5

编辑/更新:Xcode 11?斯威夫特 5

let sortedArray = array.sorted { 
let dataDict1 = responseDict.valueForKey("Data")
self.customerArray = dataDict1!.valueForKey("Customers") as! NSMutableArray

var tempArray = NSMutableArray()
for  index in self.customerArray {
   tempArray.addObject(index.valueForKey("Customer") as! NSMutableDictionary)
}

let descriptor: NSSortDescriptor =  NSSortDescriptor(key: "name", ascending: true, selector: "caseInsensitiveCompare:")
let sortedResults: NSArray = tempArray.sortedArrayUsingDescriptors([descriptor])
self.customerArray = NSMutableArray(array: sortedResults)
["d"] as? Int ?? .zero < ["d"] as? Int ?? .zero } print(sortedArray) // "[[b: moe, a: larry, d: 2, c: curly], [b: dickory, a: hickory, d: 5, c: dock], [b: blind, a: three, d: 6, c: mice]]"


let mySortedArray = myArray.sorted(by: {(int1, int2)  -> Bool in
    return ((int1 as! NSDictionary).value(forKey: "d") as! Int) < ((int2 as! NSDictionary).value(forKey: "d") as! Int) // It sorted the values and return to the mySortedArray
  }) 

print(mySortedArray)

myArray.removeAllObjects() // Remove all objects and reuse it

myArray.addObject(from: mySortedArray)

print(mySortedArray)

回答by Amol Pokale

when we parse the data then we can sort by using NSSortDescriptor

当我们解析数据时,我们可以使用 NSSortDescriptor 进行排序

##代码##

回答by M VIJAY

In Swift

在斯威夫特

##代码##

it is easy to arrange the array of dictionary value in ascending order. It doesn't need any loops.

按升序排列字典值数组很容易。它不需要任何循环。