swift map filter reduce flatMap compactMap 的用法

 

    struct Person {
        var age: Int
        var name: String
    }
    
    func getAges(people: [Person]) -> [Int] {
        return people.compactMap { $0.age }
    }
 let r1 = 0...5
        let r2 = [0,1,2,3,4,5]
        print(r1,r2)
        print("map的用法:", r1.map{$0*2} , r2.map{$0*2})
        print("filter的用法:",r1.filter{$0>2})
        print("reduce的用法:",r1.reduce(50,{$0 + $1}))
        let numbersCompound = [[1,2,3],[4,5,6]];
        let flatRes = numbersCompound.flatMap{ $0.map{ $0} }
        print("flatMap的用法:",flatRes)
        let possibleNumbers = ["1", "2", "three", "///4///", "5"]
        let compactMapRes: [Int] = possibleNumbers.compactMap { str in Int(str) }
        print("compactMap的用法:",compactMapRes)
        print( "compactMap的高级用法:",getAges(people: [Person(age: 10, name: "100"),Person(age: 100, name: "100"),Person(age: 1000, name: "100")]))

        let rigou = [1, 2, 3, nil, nil, 4, 5] //神奇的空值过滤
        let rigouNewArr = rigou.compactMap { $0 }
        print(rigouNewArr)
        
        let numbers = [1, 2, 3, 4]
        let mapped = numbers.map {Array(repeating: $0, count: $0) }
        let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
        print(mapped)
        print(flatMapped)
        

 

转载于:https://my.oschina.net/zhaodacai/blog/1797970

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值