Ios 按值作为数组的Swift排序字典

Ios 按值作为数组的Swift排序字典,ios,swift,sorting,uicollectionview,Ios,Swift,Sorting,Uicollectionview,大家好,我有structDatas(),其中包含带日期的字段start。我有24个对象,我想将其添加到集合中并按时间对集合进行排序(.start字段)。我试过stack的答案,但不是我的情况 var todaysTimes = [Int:[Datas]]() struct Datas { var id: Int var isVisited: Bool var start: Date var end: Date } 配置单元 private func configureCell(colle

大家好,我有structDatas(),其中包含带日期的字段start。我有24个对象,我想将其添加到集合中并按时间对集合进行排序(.start字段)。我试过stack的答案,但不是我的情况

var todaysTimes = [Int:[Datas]]()


struct Datas {

var id: Int
var isVisited: Bool
var start: Date
var end: Date
}
配置单元

private func configureCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {

    let availableSessionTimeCell = collectionView.dequeueReusableCell(withReuseIdentifier: availableSessionCell, for: indexPath) as! EVAvailableSessionTimeCell
    let dataItem = todaysTimes[clinicSection[indexPath.section]!]![indexPath.row]

   availableSessionTimeCell.dateLabel.text = Date.time(day: dataItem.start)

    return cell
}

在调用configureCell之前,必须对阵列进行排序。因此,在viewDidLoad方法中,应该使用如下内容

dates.sort(按:{(p1:Datas,p2:Datas)->Bool-in
返回p1.start>p2.start
})
在这之后你就可以走了

不幸的是,为字典排序更难实现


本文将对此进行讨论。

在调用configureCell之前,必须对阵列进行排序。因此,在viewDidLoad方法中,应该使用如下内容

dates.sort(按:{(p1:Datas,p2:Datas)->Bool-in
返回p1.start>p2.start
})
在这之后你就可以走了

不幸的是,为字典排序更难实现


本文将对此进行讨论。

据我所知,您希望对字典中的对象数据数组进行排序。但不要对
词典本身进行排序。如果您想对字典中的每个
(即
[Datas]
)进行排序
键值
,那么在
viewDidLoad()
中,您可能可以按照自己的意愿对数据中的数组进行排序(要么
升序
要么
降序

您可以通过在字典中循环并按如下方式对值进行排序来实现:

for (id, datas) in todaysTimes {
        todaysTimes[id] = datas.sorted(by: { $0.start.compare($1.start) == .orderedDescending })
    }
对于完整的示例,您可以在以下方面进行尝试:


据我所知,您希望对字典中的对象数据数组进行排序。但不要对
词典本身进行排序。如果您想对字典中的每个
(即
[Datas]
)进行排序
键值
,那么在
viewDidLoad()
中,您可能可以按照自己的意愿对数据中的数组进行排序(要么
升序
要么
降序

您可以通过在字典中循环并按如下方式对值进行排序来实现:

for (id, datas) in todaysTimes {
        todaysTimes[id] = datas.sorted(by: { $0.start.compare($1.start) == .orderedDescending })
    }
对于完整的示例,您可以在以下方面进行尝试:


您只需结合使用
forEach(:)
sorted(:)
即可实现该功能,即

var todaysTimes = [Int:[Datas]]()
todaysTimes.forEach { (key,value) in
    let newValue = value.sorted(by: { $0.start < $1.start }) //will sort in ascending order
    todaysTimes[key] = newValue
}

您只需结合使用
forEach(:)
sorted(:)
即可实现该功能,即

var todaysTimes = [Int:[Datas]]()
todaysTimes.forEach { (key,value) in
    let newValue = value.sorted(by: { $0.start < $1.start }) //will sort in ascending order
    todaysTimes[key] = newValue
}
可能的重复可能的重复