Swift Learning notes 2--functions, closures

Source: Internet
Author: User
Tags closure variadic

Read Catalogue

    • Function
    • Closed Package

Before learning Swift Personal notes, according to Github:the-swift-programming-language-in-chinese Learning, summary, will be important content extraction, understand and organize for learning notes, convenient for later query. For details, refer to The-swift-programming-language-in-chinese, or Apple's official English version of the document

The current version is swift2.2

Function
func sayHello(personName: String, alreadyGreeted: Bool) -> String { if alreadyGreeted { return sayHelloAgain(personName) } else { return sayHello(personName) }}
function parameter name (functions Parameter Names)

The function arguments have an external parameter name (external parameter name) and a local parameter name (local parameter name). The external parameter name is used to label the arguments passed to the function when the function is called, and the local parameter names are used inside the implementation of the function.

func someFunction(firstParameterName: Int, secondParameterName: Int) {    // function body goes here // firstParameterName and secondParameterName refer to // the argument values for the first and second parameters}someFunction(1, secondParameterName: 2)

In general, the first parameter omits its external parameter name, and the second and subsequent arguments use its local parameter name as the external argument name. All parameters must have a unique local parameter name. Although multiple parameters can have the same external parameter name, different external parameter names can make your code more readable.

You can specify an external parameter name in front of the local parameter name, separated by a space:

func someFunction(externalParameterName localParameterName: Int) {    // function body goes here, and can use localParameterName // to refer to the argument value for that parameter}

If you provide an external parameter name (including the case of the local parameter name as the external argument name), the function must use the external parameter name when it is called. If you want to ignore external parameter names, use _ instead

Default parameter value (defaults Parameter values)

You can define a default value (Deafult values) for each parameter in the function body. When the default value is defined, this parameter can be ignored when calling this function.

func someFunction(parameterWithDefault: Int = 12) {}someFunction(6) // parameterWithDefault is 6someFunction() // parameterWithDefault is 12

Place the parameter with the default value at the end of the function argument list. This guarantees that the order of the non-default arguments is consistent when the function is called, and makes the same function clearer when invoked under different circumstances. But not at the end.

Variable parameters (Variadic Parameters)

A mutable parameter (variadic parameter) can accept 0 or more values. When a function is called, you can use a mutable parameter to specify that the function parameter can be passed in an indeterminate number of input values. By adding (...) after the variable type name. ) to define a mutable parameter.

The passed-in value of a mutable parameter becomes an array of this type in the function body. For example, a Double named numbers ... Variable parameter, which can be used as an array constant in the function body as a [Double] type called numbers.

Calculate the average of arithmeticFuncArithmeticmean(Numbers:double ...) -Double { var total: double = 0 for number in   numbers {total + = number} return total/ do Uble (numbers.  Count)}arithmeticmean (1, 2, 3, 4, 5)//using Anyobject is similar to the print function of func alvalible (Num:anyobject ...) { print (num[0],num[1])}              
Constant parameters and variable parameters

function parameters are constants by default. Attempting to change the value of a parameter in the function body causes a compilation error.
Define variable parameters by adding the keyword var before the parameter name:

func alignRight(var astring: String) -> String { astring += "123" return astring}

Swift is value-passed, the variable-parameter scope is only inside the function, does not affect the caller, and the pointer in C is not the same, if you want to achieve the effect of the C pointer, you can use the input and output parameters

Input and OUTPUT parameters

Variable parameters, as described above, can only be changed within the function body. If you want a function that modifies the value of a parameter and wants it to persist after the function call ends, define the parameter as an input-output parameter (in-out Parameters). Arguments must be variable at the time of invocation, plus &

func swapTwoInts(inout a: Int, inout _ b: Int) { let temporaryA = a a = b b = temporaryA}var someInt = 3var anotherInt = 107swapTwoInts(&someInt, &anotherInt)

Input and output parameters cannot have default values, and mutable parameters cannot be marked with inout. If you mark a parameter with inout, this parameter cannot be marked by Var or let.

function parameters
func addTwoInts(a: Int, _ b: Int) -> Int { return a + b}func printHelloWorld() { print("hello, world")}

The type of the first function (Int, Int) -> Int , which can be interpreted as "This function type has two parameters of type int and returns the value of an int type." ”。 A second() -> Void

In Swift, the function type is used just like other types. For example, you can define a constant or variable of type function, and assign the appropriate function to it:

var mathFunction: (Int, Int) -> Int = addTwoIntsmathFunction(2, 3) // 直接使用

This can be interpreted as:

"Defines a variable called mathfunction, which is a ' function ' that has two parameters of type int and returns the value of an int, and the new variable points to the Addtwoints function."

Just like other types, when assigning a function to a constant or variable, you can let Swift infer its function type:

let anotherMathFunction = addTwoInts

parameter is a function type

func printMathResult(mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) { print("Result: \\(mathFunction(a, b))")}

function type as return type

func stepForward(input: Int) -> Int { return input + 1}func stepBackward(input: Int) -> Int { return input - 1}func chooseStepFunction(backwards: Bool) -> (Int) -> Int { return backwards ? stepBackward : stepForward}
Nested functions

Nested functions (Nested Functions)
All the functions you see in this chapter are called Global functions, which are defined in the global domain. You can also define functions in other function bodies, called nested functions (nested functions).

By default, nested functions are invisible to the outside world, but can be called by their peripheral functions (in the case of nested functions chooseStepFunction ). A peripheral function can also return one of its nested functions so that the function can be used in other domains.

You can override Choosestepfunction (_:) in a way that returns a nested function. Function:

FuncChoosestepfunction(Backwards:bool) (INT)Int {FuncStepforward(Input:int)Int {return input +1}FuncStepbackward(Input:int)Int {Return input-1} return backwards? Stepbackward:stepforward}var currentvalue =4 letMovenearertozero = choosest Epfunction (CurrentValue > 0)//Movenearertozero now refers to the nested Stepforward () function whileCurre Ntvalue ! = 0 { print ("\ \ (currentvalue) ... ") CurrentValue = Movenearertozero (currentvalue)}print (" zero! ") //-4 ... //-3 ... //-2 ... //-1 ... //zero!                 
Closed Package

The closure expression syntax has the following general form:

{ (parameters) -> returnType in    statements}

The closure expression syntax can use constants, variables, and inout types as arguments, and cannot provide default values. You can also use variable parameters at the end of the parameter list. Tuples can also be used as parameters and return values.

sort(_:)Method accepts a closure that requires passing in two values that are the same as the array element type, and returns a Boolean value indicating whether the first parameter passed in after the sort ends is preceded or followed by the second argument. If the first parameter value appears before the second parameter value, the sort closure function needs to return true and vice versa to return false. The sort function returns the elements inside the array to the S1,S2 two parameters in the same bubble sort order, and then compares them.

The code for the closure expression version that corresponds to the function:

String, s2: String) -> Bool in    return s1 > s2})

In an inline closure expression, however, both the function and the return value type are written in curly braces, not outside the curly braces.
The function body part of the closure is introduced by the keyword in. The keyword indicates that the closure parameter and the return value type definition have been completed and the closure function body is about to begin.

Because the sort closure function is sort(_:) passed in as a parameter to a method, Swift can infer the type of its parameter and return value. sort(_:)method is called by a string array, so its argument must be a (String, String) -> Bool function of type. This means that the (String, String) and bool types do not need to be part of the definition of a closure expression. Because all types can be inferred correctly, the return arrows (-a) and the parentheses around the parameters can also be omitted:

reversed = names.sort( { s1, s2 in return s1 > s2 } )

In fact, in any case, when a closure constructed by an inline closure expression is passed as a parameter to a function or method, it is possible to infer the closure parameter and the return value type. This means that when a closure is a function or method parameter, you rarely need to construct an inline closure with a full format.

A single-line expression closure can implicitly return the result of a single-line expression by omitting the return keyword, as the previous version example can be rewritten as:

reversed = names.sort( { s1, s2 in s1 > s2 } )

In this example, the second argument function type of the sort (_:) method is clear that the closure must return a bool type value. Because the closure function body contains only a single expression (S1 > S2), the expression returns the bool type value, so there is no ambiguity and the return keyword can be omitted.

Parameter name abbreviation

Swift automatically provides parameter name abbreviations for inline closures, and you can call the parameters of closures directly through $0,$1,$2, and so on.

Trailing closures (Trailing Closures)

If you need to pass a long closure expression as the last argument to a function, you can use a trailing closure to enhance the readability of the function. A trailing closure is a closure expression that is written after the function brackets, and the function supports calling it as the last argument:

func someFunctionThatTakesAClosure(closure: () -> Void) { // 函数体部分}// 以下是不使用尾随闭包进行函数调用someFunctionThatTakesAClosure({ // 闭包主体部分})// 以下是使用尾随闭包进行函数调用someFunctionThatTakesAClosure() { // 闭包主体部分}

A string sort closure that is used as the sort (_:) method parameter in the closure expression Syntax section can be rewritten as:

reversed = names.sort() { $0 > $1 }

If the function needs only one parameter of the closure expression, you can even omit () when you use a trailing closure:

reversed = names.sort { $0 > $1 }

map(_:)function, which takes a closure with a parameter and a return value, it iterates through each element of the Sortarr array and assigns it to the closure parameter, and the return value of the closure will form a new array as the final return of the map function. The newly produced array element corresponds to the previous array one by one

let sortArr = [1,2,3,4]let strArr = sortArr.map{ (temp) -> String in return "\\(temp + 3)"}
Capture value (capturing values)

Closures can capture constants or variables in the context in which they are defined. Even if the original scope for defining these constants and variables no longer exists, the closures can still reference and modify these values in the closure function body.

Escape Closure Package

When a closure is passed as a parameter to a function, but the closure is executed after the function is returned, we call the closure escaping from the function. You can label @noescape before the parameter name to indicate that the closure is not allowed to "escape" the function, that is, the completion of the function after the closure is released. Compiler error if forcing a closure assignment to a global variable that does not allow "escape"

When you pass a closure as a parameter to a function, you get the same delay evaluation behavior.

// customersInLine is ["Alex", "Ewa", "Barry", "Daniella"]func serveCustomer(customerProvider: () -> String) { print("Now serving \\(customerProvider())!")}serveCustomer( { customersInLine.removeAtIndex(0) } )// prints "Now serving Alex!"

serveCustomer(_:)Accept an explicit closure that returns the customer's name. The following version of this serveCustomer(_:) completes the same operation, but it does not accept an explicit closure, but instead receives an auto-closure by marking the parameter as @autoclosure. You can now call this function as a function that accepts a string type argument. The Customerprovider parameter is automatically converted to a closure because the parameter is marked with the @autoclosure attribute.

// customersInLine is ["Ewa", "Barry", "Daniella"]func serveCustomer(@autoclosure customerProvider: () -> String) { print("Now serving \\(customerProvider())!")}serveCustomer(customersInLine.removeAtIndex(0))// prints "Now serving Ewa!"

The @autoclosure feature implies the @noescape feature, and if you want the closure to "escape", you should use the @autoclosure (escaping) feature.

Swift Learning notes 2--functions, closures

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.