官术网_书友最值得收藏!

A composed function with custom operator

Let's define a new custom operator to use instead of our composed function:

precedencegroup AssociativityLeft { 
associativity: left
}

infix operator |> : AssociativityLeft
func |> <T, V>(f: @escaping (T) -> V, g: @escaping (V) -> V ) -> (T) -> V {
return { x in g(f(x)) }
}

let composedWithCustomOperator = extractElements |> formatWithCurrency
composedWithCustomOperator("10,20,40,30,80,60")
// The result will be: ["10$", "20$", "40$", "30$", "80$", "60$"]

In this example, we have defined a new operator, |>, that takes two generic functions and combines them, returning a function that has the first function's input as the parameter and the second function's return as the return type.

As this new operator is going to combine two functions and is binary, we defined it as infix. Then we need to use the operator keyword. The next step will be to choose the notation for our new custom operator. As we will group functions to the left, we need to specify it as associativity left.

To be able to use this operator, we need to define a corresponding function. Our function takes two functions as follows:

  • f: This function takes a generic type of T and returns a generic type of V
  • g: This function takes a generic type of V and returns a generic type of V

In our previous example, we had the following functions:

  • extractElements - String -> [String]
  • formatWithCurrency - [String] -> [String]

So T becomes String and V becomes [String].

Our |> function returns a function that takes a generic type of T and returns a generic type of V. We need to receive the String -> [String] from the composed function so, again, T becomes String and V becomes [String].

Using our|> custom operator makes our code more readable and less verbose. Do not worry about @escaping for now, we will talk about it in the Closures--Capturing values section of this chapter.

主站蜘蛛池模板: 航空| 习水县| 云阳县| 合肥市| 太白县| 吴堡县| 绩溪县| 阿图什市| 蒙自县| 手游| 芜湖县| 黑河市| 抚远县| 石家庄市| 天台县| 江永县| 兴仁县| 桐梓县| 年辖:市辖区| 永德县| 太白县| 邵东县| 余干县| 乐清市| 鄯善县| 台湾省| 宜宾市| 乌兰浩特市| 罗定市| 阳山县| 武安市| 米易县| 金昌市| 治县。| 新源县| 平谷区| 嘉定区| 平度市| 宜州市| 崇明县| 顺平县|