用于函数式编程的一些基本工具
简单地接收一个值但不做任何处理的函数。适用于测试和模拟。例如:
stuff.forEach(blackhole)
类似于 blackhole
,这个函数简单地接收一个值但不做任何处理。与 blackhole
不同,它总是在生产代码中被优化掉。适用于需要回调函数的场景,而你回调后不需要做任何事情。例如:
myObject.someAsyncFunction(onComplete: null)
一个简单的调用给定函数的工具函数。它适用于压缩高阶函数。例如:
let someFunctions: [BlindCallback] = [
{ print("Hello") },
{ print("World!") },
]
someFunctions.forEach(call)
将一个非柯里化函数转换为柯里化函数。例如:
let add = curry(+)
[1, 2, 3, 4].map(add(4)) // [5, 6, 7, 8]
简单地返回它所接收到的值。适用于重用高阶函数的输入。例如:
let withoutNils = arrayOfOptionals.compactMap(echo)
它也适用于扁平化生成器集合。例如:
let values = generators.map(echo)
也适用于提供一个可预测的测试函数。例如:
Lazy(initializer: echo("Foo"))
简单地返回一个具有常量输出的函数。这在创建总是需要相同输出的测试/预览时非常有用。
Lazy(initializer: constant("Foo"))
MyView(textTranslator: constant("Bar")) // imagining `textTranslator` is like `(String) -> String`
将任何返回 Bool
的函数转换为返回相反值的函数。例如:
public extension Array {
func exclude(by filter: @escaping Transformer<Element, Bool>) -> some LazySequenceProtocol {
self.lazy.filter(!mapper)
}
}
一些常用函数的类型别名
BlindCallback
和 ThrowingBlindCallback
Callback
和 ThrowingCallback
Transformer
和 ThrowingTransformer
map
函数的那种Filter
和 ThrowingFilter
filter
函数的那种Generator
和 ThrowingGenerator
@autoclosure
中一样Reducer
和 ThrowingReducer
reduce
函数的那种AllocationReducer
和 ThrowingAllocationReducer
reduce
函数的那种。通常比 Reducer
慢。Combinator
和 ThrowingCombinator
CurriedCombinator