美文网首页
Swift 高阶函数

Swift 高阶函数

作者: 派大星的博客 | 来源:发表于2018-11-16 22:23 被阅读0次

高阶函数之Reduce

public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

第一个参数是:result of combining the elements of the sequence的初始化数据。如数组求和的 let sum = 0

第二个参数是:给定闭包,闭包的第一个参数是:上次combining的结果result, 第二个参数是数组的元素element

let stringArray = ["Objective-C", "Swift", "Python", "HTML5", "C","C++"]

let resultStr = stringArray.reduce("Hi , I'm") { (result, element) -> String in
    print(result)
    return result + ", " + element
}
print(resultStr)

let count = stringArray.reduce(0) { (result, element) -> Int in
    result + element.count
}

输出:
Hi , I'm
Hi , I'm, Objective-C
Hi , I'm, Objective-C, Swift
Hi , I'm, Objective-C, Swift, Python
Hi , I'm, Objective-C, Swift, Python, HTML5
Hi , I'm, Objective-C, Swift, Python, HTML5, C
Hi , I'm, Objective-C, Swift, Python, HTML5, C, C++
31


高阶函数之Map

作用是遍历时修改item;map并不会修改实例值, 而且新建一个拷贝

public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { (str) -> Int in
    str.count
}
let lowercaseNames2 = cast.map {
    $0.lowercased()
}
let letterCounts = cast.map {
    $0.count
}

let array = [1, 2, 3]
//数组每个元素转成String类型
let str1 = array.map({
    "$\($0)"}
)
//遍历时可以添加条件判断逻辑
let str2 = array.map{ param -> Int in
    if param%2 == 0 {
        return param * 10
    } else {
        return param
    }
}

高阶函数之 flatMap && compactMap

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

注意:flatMap 在4.1被废弃,之后用compactMap.

    @available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value")
    public func flatMap(_ transform: (Element) throws -> String?) rethrows -> [String]

功能跟map类似; 区别是flatMap会过滤nil元素, 并解包Optional

let possibleNumbers = ["1", "2", "three", "4", "5"]

let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]

let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
// [1, 2, 5]

let a = [5, 8, 5, 7, 1, 2, 3, 6,9]
let flatMapArray = a.flatMap { (item) -> [Int] in
    return [item, 100]
}
// [5, 100, 8, 100, 5, 100, 7, 100, 1, 100, 2, 100, 3, 100, 6, 100, 9, 100]


高阶函数之filter

let b = ["aaa", "bbbb", "ccccc","bbbbc", "cccccb","b"]
let c = b.filter { (item) -> Bool in
    return item.count > 4
}

let a = [5, 8, 5, 7, 1, 2, 3, 6,9]
var tmp = a.filter { (item) -> Bool in
    return item > 5
}

相关文章

网友评论

      本文标题:Swift 高阶函数

      本文链接:https://www.haomeiwen.com/subject/dpmvfqtx.html