Swift Study Notes-functions and closures

Source: Internet
Author: User

Import Foundation

// 1. Define and call a function
// Use func as the prefix. The return arrow-> indicates the return type of the function.
Func sayhello (Name: string)-> string {
Let greeting = "hello" + name + "! "
Return greeting
}

Println (sayhello ("Anna "))

 

// 1.1 function parameters and return values
// The function can have multiple input parameters, which are written in parentheses and separated by commas (,).
Func minusresult (START: int, end: INT)-> int {
Return end-start
}

Println (minusresult (1, 10 ))

// 1.2 no Parameter Function
Func sayhelloworld ()-> string {
Return "Hello World"
}
Println (sayhelloworld ())


// 1.3 No Return Value Function
/*
Strictly speaking, although no return value is defined, the saygoodbye function returns a value.
A function that does not define the return type will return a special value called void. It is actually an empty tuple. It can be written as () without any elements ().
*/
Func saygoodbye (Name: string ){
Println ("Goodbye, \ (name )")
}
Println (saygoodbye ("Dave "))


// 1.4 Multiple Return Value Functions
// You can use the tuple type to return multiple values as a composite value from the function.
Func count (string: string)-> (vs: int, CS: int, OS: INT ){
VaR vowels = 0, consonants = 0, others = 0
For character in string {
Switch string (character). lowercasestring {
Case "A", "E", "I", "O", "U ":
++ Vowels
Case "B", "C", "D", "F", "g", "H", "J", "k", "L ", "M ",
"N", "P", "Q", "r", "S", "T", "V", "W", "X", "Y ", "Z ":
++ Consonants
Default:
++ Others
}
}

Return (vowels, consonants, others)
}
Let Total = count ("some arbitrary string! ")
Println ("\ (total. VS) vowels and \ (total. CS) consonants ")


// 2 function parameter name
// 2.1 External Parameter Name

// Demo: concatenates two strings to demonstrate the advantages of using external parameters.
/*
// Do not use external parameters
Func join (S1: String, S2: String, Joiner: string)-> string {
Return S1 + Joiner + S2
}
Println (join ("hello", "world", ",") // the usage of these three strings is not very clear
*/

/*
// Use the External Parameter Name
// To make the usage of these strings more obvious, we add an external parameter name for the join function.
Func join (string S1: String, tostring S2: String, withjoiner Joiner: string)-> string {
Return S1 + Joiner + S2
}
// The use of external parameter names is more expressive and fluent, while keeping the function body readable and with clear intentions
Println (join (string: "hello", tostring: "world", withjoiner :","))
*/


// 2.2 abbreviated External Parameter Name
// If you need to provide external parameter names, but the local parameter names have been defined, you do not need to write these parameter names twice. On the contrary, you only need to write the parameter name once and use the # As the prefix. This tells swift to use this parameter name as the local and external parameter names.
Func containscharacter (# string: String, # charactertofind: character)-> bool {
For character in string {
If character = charactertofind {
Return true
}
}

Return false
}

// Define the parameter name so that the function body is more readable and clear, and can be called in an unambiguous way
Let containsavee = containscharacter (string: "qwertyuiop", charactertofind: "Y ")
Println (containsavee)


// 2.3 default parameter value
// You can define the default value for each parameter in the function body. When the default value is defined, you can skip this parameter when calling this function.
Func join (string S1: String, tostring S2: String, withjoiner Joiner: String = ",")-> string {
Return S1 + Joiner + S2
}
Let str1 = join (string: "hello", tostring: "world", withjoiner: "-") // specify the third parameter
Println (str1)

Let str2 = join (string: "hello", tostring: "world") // The third parameter is not specified. The default value is used for the third parameter.
Println (str2)

// 2.4 default parameter External Parameter Name
// When you do not provide an external parameter name for a parameter with the default value, swift automatically provides an external name. At this time, the external parameter name is the same as the local name, just as you have already written the well number (#) before the local parameter name.
Func join (S1: String, S2: String, Joiner: String = "")-> string {
Return S1 + Joiner + S2
}
Let str3 = join ("hello", "world", Joiner :"-")
Println (str3)


// 3. variable parameters
// Input the variable parameter value in the function body as an array of this type. For example, a variable parameter of the double... type called numbers can be used as an array constant of the double [] type called numbers in the function body.
// A function can have at most one variable parameter
// Variable parameters must be placed at the end of the parameter table
Func aritheticmean (numbers: Double...)-> double {
VaR Total: Double = 0
For number in numbers {
Total + = Number
}
Return total/double (numbers. Count)
}
Println (aritheticmean (1.2, 3.5, 4.6 ))
Println (aritheticmean (1.2, 3.5, 4.6, 9.0, 10.0 ))

 

// 4. Constant parameters and variable parameters
// Function parameters are constants by default. But sometimes it is useful if the parameters passed in the function can be modified. You can specify one or more parameters as variable parameters to avoid defining new variables in the function. Variable parameters are not constants. You can use them as new modifiable replicas in functions.
// Add the keyword var before the parameter name to define the Variable Parameter
Func alignright (VAR string: String, Count: int, pad: character)-> string {
Let amounttopad = count-countelements (string)
For _ in 1... amounttopad {
String = pad + String
}
Return string
}

Let originalstring = "hello"
Let paddedstring = alignright (originalstring, 10 ,"-")
Println ("originalstring:" + originalstring)
Println ("paddedstring:" + paddedstring)

 


// 5 Input and Output Parameters
// Variable parameters, as described above, can only be changed in the function body. If you want a function to modify the value of a parameter, and want these modifications to still exist after the function call ends, this parameter should be defined as an in-out parameters parameter ).

// Define an input/output parameter, and add the inout keyword before the Parameter
// Input/output parameters cannot have default values, and variable parameters cannot be marked with inout. If you use inout to mark a parameter, this parameter cannot be marked by VAR or let.
Func swaptwoints (inout A: int, inout B: INT ){
Let temp =
A = B
B = temp
}

// Only one variable can be input and output.
VaR someint = 3
VaR anotherint = 7
// When the input parameter is used as the input and output parameters, add & before the parameter to indicate that this value can be modified by the function.
Swaptwoints (& someint, & anotherint)
Println ("someint is now \ (someint), and anotherint is now \ (anotherint )")

 


// 6. function type (it is a data type, similar to function pointers in C language and block in OC language)
// Three steps: 1. Define a function; 2. Declare a function type variable or constant; 3. assign a value to the function type variable.
// 1. Define a function
Func addtwoints (A: int, B: INT)-> int {
Return A + B
}

Func sum (A: int, B: INT)-> int {
Return a-B
}

Func printhelloworld ()
{
Println ("Hello, world ")
}

/*
// 2. Declare a variable named mathfunction. The type is a function with two int parameters and an int value returned'
VaR mathfunction: (INT, INT)-> int

// 3. assign values to function type variables
Mathfunction = addtwoints


// Since it is a variable, we can assign a value to mathfunction again.
Mathfunction = sum
*/

/*
// Merge in two or three steps
VaR mathfunction: (INT, INT)-> Int = sum
*/

// Type derivation, which allows swift to speculate on the mathfunction type
VaR mathfunction = sum
// Mathfunction = printhelloworld // error, Type Mismatch


// 4. Use
Println ("Result: \ (mathfunction (2, 3 ))")

 

// Swift calls the c Function
Desc1 ()

// Swift calls oC
VaR funcclass = funcblock () // get the OC Class Object
Funcclass. desc2 ()

 


// 6.1 function type as parameter type
Func printmathresult (mathfun: (INT, INT)-> int, A: int, B: INT ){
Println ("Result: \ (mathfun (a, B ))")
}
Printmathresult (addtwoints, 4, 7)


/*
// 6.2 function type as return type
Func stepforward (input: INT)-> int {
Return input + 1
}
Func stepbackward (input: INT)-> int {
Println ("stepbackward ")
Return input-1
}

// Good. Are you dizzy ??? When the system is dizzy, take a rest and read the content you just mentioned. If it is not dizzy, continue.
Func choosestepfunction (backwards: bool)-> (INT)-> int {
Return backwards? Stepbackward: stepforward // return function type
}
VaR currentvalue = 3
Let movenearertozero = choosestepfunction (currentvalue> 0)
// Let movenearertozero :( INT)-> Int = choosestepfunction (true) // prototype
// Movenearertozero = stepbackward
Println ("movenearertozero: \ (movenearertozero)") // movenearertozero points to stepbackward

Println ("Result: \ (movenearertozero (10 ))")
*/

// Nested Functions
Func choosestepfunction (backwards: bool)-> (INT)-> int {
Func stepforward (input: INT)-> int {
Return input + 1
}
Func stepbackward (input: INT)-> int {
Println ("stepbackward ")
Return input-1
}
Return backwards? Stepbackward: stepforward // return function type
}
VaR currentvalue =-4
Let movenearertozero = choosestepfunction (currentvalue> 0)
Println ("nested function: \ (movenearertozero (10 ))")

 

 


// 8. Closure
// 8.1 closure expression

Let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]


// No closure is used.
Func backwards (S1: String, S2: string)-> bool {
Return S1> S2
}
// The swift Standard Library provides the sort function, which sorts the values in an array of known types based on the closure function of the output type you provide.
VaR reversed = sort (names, backwards)
Println (reversed)


// Use the closure
// The function body of the closure is introduced by the keyword in. This keyword indicates that the closure parameters and return value type definitions have been completed, and the closure function body is about to begin.
Reversed = sort (names, {(S1: String, S2: string)-> bool in
Return S1> S2
})

// Type inferred based on Context
Reversed = sort (names, {S1, S2 in return S1> S2 })


// 8.2 single expression closure implicit return
// If the closure body has only one expression, the return keyword can be omitted.
Reversed = sort (names, {S1, S2 in S1> S2 })

// 8.3 abbreviated parameter name
// $0 and $1 indicate the first and second string parameters in the closure.
Reversed = sort (names, {$0> $1 })

// 8.4 Operator Functions
// The string type of swift defines the string Implementation of greater than (> ).
Reversed = sort (names,>)


// 8.5 trailing Closure
// If you need to pass a long closure expression (so that it cannot be written in a row) as the last parameter to the function, you can use the trailing closure to enhance the readability of the function. A trailing closure is a closure expression written after the function brackets. It can be called as the last parameter.
Reversed = sort (names) {$0> $1}

Println (reversed)

 

// 8.6 capture value
Func makeincrementor (forincrement amount: INT)-> ()-> int {
VaR runningtotal = 0

// The incrementor function does not obtain any parameters, but the runningtotal and amount variables are accessed in the function body. This is because it is implemented by capturing the runningtotal and amount variables that already exist in the function body that contains it.
Func incrementor ()-> int {
Runningtotal + = Amount
Return runningtotal
}

Return incrementor
}
Let incrementbyten = makeincrementor (forincrement: 10)

// Because the value of runningtotal is changed every time this function is called, incrementor captures the reference of the current runningtotal variable instead of simply copying the initial value of this variable. Capture a reference to ensure that the makeincrementor does not disappear when it ends. It also ensures that runningtotal can continue to increase when the incrementor function is executed for the current time.
Println (incrementbyten () // 10
Println (incrementbyten () // 20
Println (incrementbyten () // 30


Let incrementbyseven = makeincrementor (forincrement: 7)
Println (incrementbyseven () // 7
Println (incrementbyten () // 40


// 8.7 closure is of reference type
// In the above example, incrementbyseven and incrementbyten are constants, but the closure pointed to by these constants can still increase the captured variable values. This is because both functions and closures are reference types.

// If you assign a closure value to two different constants/variables, both values point to the same closure and point to incrementor.
Let alsoincrementbyten = incrementbyten
Println (alsoincrementbyten () // 50

 

Swift Study Notes-functions and closures

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.