对字典数组排序(快速) [英] Sort an array of dictionary (swift)

查看:90
本文介绍了对字典数组排序(快速)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let unsorted = [{Name:Amy,age:20},{Name:Bill,age:20}]
let sortedDict = sorted(unsorted){a,b in return a.Name < b.Name}

如何根据Name键对未排序的数组排序?上面的代码似乎不起作用。

How can I sort the unsorted array according to the Name key? Above code seems doesn't work.

推荐答案

如果您使用的是自定义结构而不是a,则您的排序语法(几乎)有效字典

Your sorting syntax works (almost) if you are using a custom struct rather than a dictionary

struct Person {
  let name : String
  let age : Int
}

let unsortedPeople = [Person(name:"Bill", age:20), Person(name:"Amy", age:20)]

现在您可以使用 sorted 函数

let sortedDict = unsortedPeople.sorted{ $0.name < $1.name }

这篇关于对字典数组排序(快速)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆