Swift --棒棒糖2--filter,map,compactMap,reduce,sort高阶函数

在这里插入代码片Swift提供了很多很便捷的高阶函数,避免了使用for循环,创建临时数组等繁琐的手段就能得到你想要的结果,代码看起来简洁明了,行云流水

struct Student {
    
    
    var name:String
    var number:Int
    var sex:Float
    var address:String
}


let students = [
            Student(name: "张三", number: 1, sex: 0, address: "北京"),
            Student(name: "李四", number: 2, sex: 1, address: "上海"),
            Student(name: "王五", number: 3, sex: 1, address: "广州"),
            Student(name: "赵六", number: 4, sex: 0, address: "深圳")
        ]

***一:Filter的使用,从原数组中找出满足添加的元素,形成一个新的较之原数组元素变少的的数组***
let name = students.filter {
    
     (student) -> Bool in      
            return student.sex == 0
        }
let name1 = students.filter {
    
     $0.sex == 0}
print("===\(name)")
print("===\(name1)")

结果:[hello.Student(name: "张三", number: 1, sex: 0.0, address: "北京"), hello.Student(name: "赵六", number: 4, sex: 0.0, address: "深圳")]

***二:Map的使用, 是拿出原数组中元素的某一属性, name或者number或者sex或者address,形成一个与原数组类型完全不一致某类型的集合***
let aa = students.map {
    
     $0.name }
print("===\(aa)")

结果:["张三", "李四", "王五", "赵六"]

***三:CompactMap的使用***

let students2 = [
            Student(name: "张三", number: 1, sex: 0, address: "北京"),
            nil,
            Student(name: "李四", number: 2, sex: 1, address: "上海"),
            Student(name: "王五", number: 3, sex: 1, address: "广州"),
            Student(name: "赵六", number: 4, sex: 0, address: "深圳")
        ]
 这个数组较之上面的数组,里面有一个元素为nil

let student2 = students2.compactMap {
    
     $0?.name }
print("===\(student2)")

结果:["张三", "李四", "王五", "赵六"],可见它较之于Map可以排空原数组中的空元素后再进行新元素整合形成新的不同于原数组类型的数组。

***四:Reduce的使用*** //reduce取简化之意而非减少

let reduceStudent = students.reduce(10) {
    
     (a, student) -> Int in
            return a + student.number
        }
print("=====\(reduceStudent)")

a代表你基于运算前,初始化了一个值10, a 用来存储每一次(相当于for循环)计算的值临时存在a中
a + studentnumber ----- 10 + 1 = 11 
a + studentnumber ----- 11 + 2 = 13
a + studentnumber ----- 13 + 3 = 16
a + studentnumber ----- 16 + 4 = 20
结果:20

***五:sort排序***
        let sortA = students.sorted(by: {
    
    a,b in
            a.number < b.number
        })
print("----\(sortA)")
按number从小到大重新排序原数组,原数组类型不变

结果:[hello.Student(name: "张三", number: 1, sex: 0.0, address: "北京"), hello.Student(name: "李四", number: 2, sex: 1.0, address: "上海"), hello.Student(name: "王五", number: 3, sex: 1.0, address: "广州"), hello.Student(name: "赵六", number: 4, sex: 0.0, address: "深圳")]







猜你喜欢

转载自blog.csdn.net/SoftwareDoger/article/details/105875877