Swiftional
Swiftional 引入了一些与 Swift 标准库互补的函数式原语。
为编写略带函数式编程风格的 Swift 代码而创建。
函数
curry
将非柯里化函数转换为柯里化函数。示例
(A, B) -> R
becomes
(A) -> (B) -> R
uncurry
将柯里化函数转换为非柯里化函数。示例
(A) -> (B) -> R
becomes
(A, B) -> R
partial
偏应用。将一个参数应用于一个函数。示例
(A, B) -> R
with applied first argument becomes
(B) -> R
identity
合取子函数。返回输入值而不改变它。constant
常量合取子函数。忽略函数参数并始终返回提供的值。flip
翻转函数的参数。示例
(A, B) -> R
becomes
(B, A) -> R
with
通过指定的闭包和提供的属性作为接收者来调用指定的闭包,并返回其结果。ignored
忽略函数返回值,并始终返回 `Void`。weakify
弱化函数。示例
// Instead of this:
someObject.onActionClosure = otherObject.someFunc // `otherObject` captured by strong reference
// Use operator:
someObject.onActionClosure = weakify(otherObject) { $0.someFunc() } // `otherObject` is weakified, not captured by strong reference
扩展
Bool
* `fold` 对 `Bool` 类型的案例分析。根据值应用提供的闭包。-
foldRun
根据此值的内稧运行提供的闭包。 -
oldEither
Case analysis for theBool
type. Applies the provided closures based on the value and returnEither
.
可选
* `fold` Case analysis for the `Optional` type. Applies the provided closures based on the content of this `Optional` value.协议
可应用
* `apply` Calls the specified closure with Self value as its receiver and returns Self value.applied
Calls the specified closure with Self value as its receiver and returns copy of Self value.
算子
>>>
组合一个函数,并返回一个返回结果,该结果是对函数 `f` 输出的 `g` 的应用。<<<
组合一个函数,并返回一个返回结果,该结果是对函数 `f` 输出的 `g` 的应用。|>
管道向前。将一个参数应用于一个函数。实例。这是
let result = h(parameter: g(parameter: f(parameter: a)))
也可以写成
let result = a |> f |> g |> h
<|
管道向前。将一个参数应用于一个函数。实例。这是
let result = h(parameter: g(parameter: f(parameter: a)))
也可以写成
let result = h <| g <| f <| a
|>>
将一个函数应用于一个参数并返回可调用的函数。实例。这是
let result = { a in f(parameter: a) }
也可以写成
let result = a |>> f
<<|
将一个函数应用于一个参数并返回可调用的函数。实例。这是
let result = { a in f(parameter: a) }
也可以写成
let result = f <<| a
~~>
异步函数组合>=>
有效函数组合?>
弱化函数。示例
// Instead of this:
someObject.onActionClosure = otherObject.someFunc // `otherObject` captured by strong reference
// Use operator:
someObject.onActionClosure = otherObject ?> { $0.someFunc() } // `otherObject` is weakified, not captured by strong reference
类型
Either
The type `Either` represents a value of one of these types, but not both: `.left(Left)` or `.right(Right)`.The Either
type is shifted to the right by convention. That is, the .left
constructor is usually used to hold errors or secondary data, while .right
is used to store a "correct", primary value - one that can be worked on further.
Wordplay: "Right" also means "Correct".