Swift # Curry function

Source: Internet
Author: User

Objective

This article, about a new feature of Swift (curry function), many iOS developers may be the first time to listen to the word, including myself, I also took a few days to summarize, I hope to help you, personal feeling biased with the development experience of the Code friends, if 0 basic understanding, Hope to give a praise,??!

If you like my article, you can pay attention to me, with the follow-up learning swift, there will be updated ing ....

What is the curry function?

Curry (currying), also called partial Evaluation, is a functional programming idea that converts a function that accepts multiple parameters into a function that receives a single parameter (the first parameter of the original function) and returns a new function technique that accepts the remaining parameters.

classcurrying{//uncurried: normal function//functions that receive multiple parameters (class-related functions, collectively referred to as methods, but here are straightforward functions, easy to understand)func Add (A:int, B:int, C:int)-int{println ("\ (a) + \ (b) + \ (c)")        returnA + B +C}//Curried: The function of curry//The curry function, which already supports this syntax in Swift, can be written directlyfunc addcur (a:int) (B:int) (C:int)-int{println ("\ (a) + \ (b) + \ (c)")        returnA + B +C}}

How do I define the curry function?

Define the curry function:

The implementation principle of the Curry function

classcurrying{/** * uncurried: normal function * **/    //functions that receive multiple parametersfunc Add (A:int, B:int, C:int)-int{println ("\ (a) + \ (b) + \ (c)")        returnA + B +C}/** * Manual implementation of the CURRY function * **/    //convert the above function to the curry function, first turn to receive the first parameter a, and return the new function that receives the remaining first parameter B (with closure)//to get everyone to understand, I'll help you break it down and see//(a:int): Parameter//(B:int), (c:int), int: function return value (a function that receives parameter B, and this function returns a function that receives the parameter C and returns a value of type Int)//defines a receive parameter A, and returns a function that receives parameter B, and returns a function that receives the parameter C and returns a value of type intfunc Add (a:int)(B:int), (C:int)int{//a function that receives the parameter B, and the function returns a function that receives the parameter C and returns a value of type int        return{(B:int)-(c:int)-Intinch          //returns a function that receives the remaining first parameter, C, and has a return result of type int         return{(c:int)-Intinch          returnA + B +C; Note: Why can I use parameter a,b,c here ??use the value of the closure to capture the attributes, even if the values are not scoped, to capture their values.            The closure automatically determines whether the captured value is a copy of the value or a value reference, or, if modified, is a value reference, otherwise the value is copied.            Note that only in closures can the a,b,c be in a closed package. }        }    }     /** * Curried: The system comes with the curry function * **/func addcur (a:int) (B:int) (C:int)-int{println ("\ (a) + \ (b) + \ (c)")        returnA + B +C}}

How to call the Curry function

Because an instance method is defined, the call requires a dependent object.

Call the Curry function:

//to create an instance of the Curry classvar curryinstance=currying ()/** * Invoke the manual implementation of the CURRY function **/var r:int= Curryinstance.add (Ten) (b: -) (c: -)//maybe a lot of people are looking at this kind of call for the first time, it feels a bit weird. //Let's review the OC creation Object [[Person alloc] init], this should all be seen, that is, send two messages, Alloc return an instance, and then call init initialization with the instance, the same above, call multiple functions, Each call returns a function and then calls the returned function again.  /** * * * Curry function Decomposition Call * * * **///let me help you break it down, it 's easier to read.//Curryinstance.add (10): Calls a receive parameter A, and returns a function that receives parameter B, and returns a function that receives the parameter C and returns a value of type int//functionb: A function that receives the parameter B, and the function returns a function that receives the parameter C, and returns a value of type intLet functionb= Curryinstance.add (Ten) //functionb (B:20): Call a function that receives parameter B, and this function returns a function that receives the parameter C and returns a value of type int//Functionc: A function that receives a parameter C and returns a value of type intLet functionc= Functionb (b: -) //Functionc (c:30): Call a receive parameter C, return a function of type int//Result: Return value of functionvar res:int= Functionc (c: -); //Is there a question here, why not call Curryinstance.add (a:10), but Curryinstance.add (Ten), Functionb (b:20), Functionc (c:30), how there is b,c, This is because Func Add (a:int)--(B:int)--(C:int) is the first parameter in this method, the default is no external parameter name, only the remaining arguments have an external parameter name, and B,c belongs to the remaining parameters. /** * * * * SYSTEM's CURRY function call * * * **/var result:int= Curryinstance.addcur (Ten) (b: -) (c: -)/** * * * The CURRY function of the system to disassemble the call * * **///Note: Swift is a strongly typed language and there are no errors here, stating that the type returned by the calling system's curry function is consistent with the manual FUNCTIONB type//Curryinstance.addcur (10): Calls a receive parameter A, and returns a function that receives parameter B, and returns a function that receives the parameter C and returns a value of type int//functionb: A function that receives the parameter B, and the function returns a function that receives the parameter C, and returns a value of type intfunctionb= Curryinstance.addcur (Ten) //Functionc: A function that receives a parameter C and returns a value of type intFunctionc= Functionb (b: -) //Result: Return value of functionRes= Functionc (c: -) //Printing the 60,60,60 description of the manual implementation of the Curry function, and the same as the system. println ("\ (r), \ (res), \ (Result)")

Use of the Curry function note

1. You must call the Curry function in the order in which the parameters are defined, otherwise you will get an error.

var result:int = curryinstance.addcur (ten)

2. The function body of the curry function is executed only once, and the curry function body is executed only when the last parameter is called. The function body is executed by Functionc (c:30). This can debug your own breakpoint .

//Curried: The function of curryfunc addcur (a:int) (B:int) (C:int)-int{println ("\ (a) + \ (b) + \ (c)")    returnA + B +C}//to create an instance of the Curry classvar curryinstance=currying ()//does not execute the Curry function bodyfunctionb= Curryinstance.addcur (Ten)//does not execute the Curry function bodyFunctionc= Functionb (b: -)//executing the curry function bodyRes= Functionc (c: -)

The example method in Swift is one of the curry functions

How do I get an instance method? You can get an instance method directly from the class.

Note: What type of function is returned by the method, but it needs to pass in a parameter (class instance) to get to it, if there is an external parameter name in the method, the external parameter name is also part of the type

To get an instance method using a class:

Another way to invoke instance methods in Swift (curry call)

// to create an instance of the Curry class  =//  Call function method  //  disassemble Call function method // 1. Get the function method  = currying.function (curryinstance)//  2. Call function Method function () 

Note: The steps are the same, first get the instance method, in the call instance method, the instance method how to call, do not need to teach.

What are the benefits of the curry function? Why use it?

Here we need to understand the functional programming ideas , recommended to see this article on functional programming

Characteristics:

1. use only "expression"(expression: simple operation, always has a return value), without "statement"(statement: Perform an operation, no return value). 2. The value is not modified, only the new value is returned .

Benefits:

1. Simple code

2. Improve Code reusability

3. Code management is convenient, independent of each other, each function is a separate module, it is easy to do unit testing.

4. Easy "Concurrent programming" because the value of the variable is not modified, it returns the new value.

The curry function is the use of functional programming ideas, so it also has the above benefits.

How to use the curry function (usability) in iOS development

Usability One: reusability

Demand 1: map Products , many interfaces have the same function modules, such as the search box.

We can use the curry function, to assemble the interface, the interface into a small module, so that the other interface has the same module, directly using the module code, to re-assemble it.

Practicality Two: latency , the Curry function code requires that the previous method call is completed before it comes to the Curry function code.

Demand 2: reading Products , an interface display, depending on the data, need to load the data before you can determine the interface display.

At this time can also use the curry function, to assemble the interface, the various modules to load the method of data extraction, and so on all loaded, in the implementation of the Curry function, the curry function is mainly to achieve interface assembly.

To illustrate:

// Combination Interface // Why to define the interface, in order to extend the program, only need to add the corresponding combination method in the interface just fine.  Protocol combineui{    , ()) (bottom: ()//  Define an interface class and follow the combined interface  Class  ui:combineui{    , ()) (bottom: (), ()) () {        //  top of the building 
            Top ()        //  build Bottom         bottom ()    }}

Click to download: source code

Source: Ah 崢 's book of Jane

Weibo: acridine a Zheng , welcome to Exchange.

|--> Copyright (c) Bing Ma.

|--> GitHub RUL: https://github.com/SpongeBob-GitHub

Swift # Curry function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.