Swift4.1 新特性compactMap函数

关于compactMap函数

苹果在Swift 4.1中新增compactMap函数,用来代替flatMap函数。

在Swift标准库中compactMap定义如下

public func compactMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

在Swift标准库中flatMap定义如下

public func flatMap(_ transform: (Element) throws -> String?) rethrows -> [String]

从定义可以看出,经过flatMap后一定变成字符串数组,而compactMap是任意类型的数组。从而compactMap使用更加灵活。

compactMap函数的应用

1.过滤 nil

let nums = [1, nil, 3, nil, 5]
let result = nums.compactMap { (item) -> Int? in
    return item
}
print(result) // [1, 3, 5]

简洁语法,可这样使用

let result = nums.compactMap { return $0 }
print(result) // [1, 3, 5]

2.类型转换

let nums = [1, 2, 3, 4, 5]
let result = nums.compactMap { (item) -> String? in
    
    return "\(item)"
}
print(result) // ["1", "2", "3", "4", "5"]

简洁语法,可这样使用

let nums = [1, 2, 3, 4, 5]
let result = nums.compactMap { return "\($0)" }
print(result) // ["1", "2", "3", "4", "5"]

3.筛选数据 - 能被4整除的数

let nums = [12, 55, 733, 77, 44]
let result = nums.compactMap { (item) -> Int? in

    if item%4 == 0 {
        return item
    }
    return nil
}
print(result) // [12, 44]

compactMa函数不仅仅以上的使用,本文只是引进门。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Harvey66

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值