swift中Dictionary的grouping by使用

今天在写一个功能的时候用到了Dictionary 的 grouping by 这个用法,代码先贴出来

import UIKit

class AlignFlowLayout: UICollectionViewFlowLayout {

    required init(itemSize: CGSize = CGSize.zero, minimumInteritemSpacing: CGFloat = 0, minimumLineSpacing: CGFloat = 0, sectionInset: UIEdgeInsets = .zero) {
        super.init()

        self.itemSize = itemSize
        self.minimumInteritemSpacing = minimumInteritemSpacing
        self.minimumLineSpacing = minimumLineSpacing
        self.sectionInset = sectionInset

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let layoutAttributes = super.layoutAttributesForElements(in: rect)!.map { 0.copy() as! UICollectionViewLayoutAttributes }
        guard scrollDirection == .vertical else { return layoutAttributes }

        // Filter attributes to compute only cell attributes
        let cellAttributes = layoutAttributes.filter({0.representedElementCategory == .cell })

        // Group cell attributes by row (cells with same vertical center) and loop on those groups
        for (_, attributes) in Dictionary(grouping: cellAttributes, by: { ($0.center.y / 10).rounded(.up) * 10 }) {
            // Set the initial left inset
            var leftInset = sectionInset.left

            // Loop on cells to adjust each cell's Origin and prepare leftInset for the next cell
            for attribute in attributes {
                attribute.frame.origin.x = leftInset
                leftInset = attribute.frame.maxX + minimumInteritemSpacing
            }
        }

        return layoutAttributes
    }
}

可以看出来这这个代码是做了一个UICollectionViewFlowLayout的自定义,是为了做UICollectionView的Items的居左显示排列,但这不是我们要研究的重点,我们需要研究Dictionary grouping by 的用法。

其实通过grouping by 这个叫法来说应该大概说明了它的含义,它应该是按照某种条件分组使用的,那下面我们来举个例子。

例如我们有一个现有数组

enum Sex{
    male,
    female
}

class Student {
    var name:String?
    var sex:Sex = Sex.male
    var age:Int = 0
}

可以看出来我们以上定义了一个枚举和一个类,类中用到了这个枚举来代表性别。比如说我们有如下一组数据。

val student1 = Student()
student1.name = "小明"
student1.sex = Sex.male
student1.age = 18

val student2 = Student()
student2.name = "小红"
student2.sex = Sex.female
student2.age = 20

val student3 = Student()
student3.name = "小童"
student3.sex = Sex.male
student3.age = 18

val students = [student1,student2,student3]

那么如果我们想用性别来把数组进行分组应该怎么写呢,我们下面来研究一下

let groups = Dictionary(grouping:students, by: {
    $0.sex
})

//对就这样用Dictionnary的grouping by 操作一下就好了,那么得到数据应该是如下这样

let groups = [Sex.male:[student1,student3], Sex.female:[student2]]
当然真是数据肯定是每个组里边的数据是实体数据,我这在这里只是表象一下,这样大家应该很好理解。

好的,写到这里应该算是明白了,我们可以动手自己写着体验一下,还可以用这种方式试着写一下按照相同年龄分组一下或者按照不同年龄段分组一下。

5 1 投票
文章评分
订阅评论
提醒
guest
0 评论
内联反馈
查看所有评论
京ICP备17066706号-1
0
希望看到您的想法,请您发表评论x