Swift4.1 新特性compactMap函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yao1500/article/details/80407358

关于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函数不仅仅以上的使用,本文只是引进门。

猜你喜欢

转载自blog.csdn.net/yao1500/article/details/80407358