Swift Learning Notes (functions)

Source: Internet
Author: User
Tags mathematical functions

Function

A function is a separate block of code used to perform a specific task. The functions in Swift are the same as those in object-c, but the declarations are not the same as the way they were written, so let's take a few examples to introduce the functions in swift. In simple terms, he is somewhat similar to the function declaration in JS, but if there is a return value, their return value is written in a different way.

First, a simple example.

//the name of the greet function//personname: A formal parameter of a function that can be separated by commas//The return value type of the->string function if no can be writtenFunc Greet (personname:string)String {Let greeting="Hello:"+ PersonName +"!"print (greeting)returngreeting;}//Call to functionGreet (personname:"Tian")
Formal parameters and return values for functions

In Swift, the formal parameters and return values of functions are very flexible, and you can define any function from a simple tool function with only one unnamed form parameter to a complex function that has an image parameter name and different formal parameter options.

Functions with no formal parameters

The function does not require a parameter to be entered, or it does not need to accept external variables to complete a specific function, example

// function func SayHelloWorld (),String    {return"Hello  World" without formal parameters "}print (SayHelloWorld ());

The definition of a function still requires a parenthesis after the name, even if it does not accept the formal argument. When the function is called, add an empty parenthesis behind the name of the function.

Functions of multi-form parameters
Func Greet (personname:string)String {Let greeting="Hello:"+ PersonName +"!"print (greeting)returngreeting;}//Call to functionGreet (personname:"Tian")//functions of multi-form parameters/*functions can be entered in multiple form parameters can be unloaded after a comma separated by the parentheses*/func greetagain (person:string)-String {return "Hello One More time"}func Secondgreet (person:string,alreadgreeted:bool)-String {ifalreadgreeted {returnGreetagain (Person:person); }Else {        returngreet (Personname:person)}}//calling FunctionsSecondgreet (Person:"Tian", alreadgreeted:false)
function with no return value
// function with no return value /*  */func thirdgreet (person:string) {    print ("hello,\ (person)  "" Tian ")

Because there is no estoppel value, the function does not have to write (-) or return type when defined

//We can also ignore the return value of a function when calling a functionFunc Printandcount (string: String),Int {print (string)    return string. Characters.count}func printwithoutcounting (string: String) {Let _= Printandcount (string:"Tianfeng")}printandcount (string:"Liantian");p rintwithoutcounting (string:"Swift")

Note: The return value can be ignored but must be returned if a function needs to return a value, if a function has a definition return type, no inverse value will not run to the end of the function, will be reported at compile time error

Functions with multiple return values

In order for the function to return multiple values as a composite return value, you can use the tuple type as the return type.

Func Minmax (Array:[int])(Min:int, max:int) {//var currentmin = array[0]//var Currentmax = array[0]//    //For value in array {//if value < currentmin {//currentmin = value;//}else if (value > Currentmax) {//Currentmax = value//        }//    }//return (Currentmin,currentmax);    return(Array.min ()!,array.max ()!)}let Minandmax= Minmax (array: [1,2,3,4,5]) print ("\ (minandmax.min) and \ (Minandmax.max)")

Optional tuple return type

If the tuple may not have a value in the return type of the function, you can use an optional tuple return type to indicate that the entire tuple may be nil. Here's an example:

Func Minmax (Array:[int]), (min:int,max:int)? {        ifArray.isEmpty {returnNil}return(Array.min ()!,array.max ()!)}//because it is an optional type, it is possible for nil to return at the time of invocation. We need to unpack the return valueiflet bounds = Minmax (array: [8,-6,102,3, in]) {print ("\ (bounds.min) and \ (Bounds.max)")}
The actual parameter label and form parameter name of the function

The formal parameters of each function contain the actual parameter label and the form parameter name. The actual parameter tag is used when calling the function, the actual parameter tag is written before each actual parameter when the function is called, and the formal parameter name is used in the implementation of the function. By default, formal parameters apply their formal parameters as actual parameter labels.

Func someFunction (firstparametername:int?,secondparametername:int?) {        = firstparametername,          = secondparametername    Else  {         return     }    +72)

The left and right form parameters must have a unique name. Although it is possible that multiple form parameters have the same actual parameter label, the only actual parameter tag helps make your code easier to read.

Specify the actual parameter label

Write the actual parameter label before the supplied form parameter name separated by a space

func someFunction (actual parameter parametername:int) {    print (" passed in parameter is: \ (parametername)"   ) 
Omit actual parameter labels
// omit actual parameter labels Func SomeFunction1 (_ Firstparametername:int, secondparametername:int) {    }somefunction1 (1 3)

Default form parameter values

You can define a default value for any form parameter of the function by assigning a value to the form parameter after the driving parameter type, and if the default value is defined, you can omit the formal argument when calling the function.

B:int,Int {    return b*))//  Although there is a default value, if you want to change it can still change the 5))

Variable form parameters

A mutable form parameter can accept values of 0 or more specific types. When calling a function, you can use the variable form parameter to declare that the number of parameters that can be passed in is variable. You can insert a three point symbol (...) by the type name of the form parameter. ) to write variable form parameters.

The value passed into the variable parameter is treated as an array of the corresponding type in the body of the function. For a chestnut, the name of a mutable parameter is the numbers type is Double ... In the body of the function it is treated as a constant array with the name numbers type is [Double].

Func Arithmeticmean (numbers:double ...),Double {    0;      for inch Numbers {        + = number    }    return total/1,2 ,3,4,5,6)
Input and output form parameters

The variable form parameter function changes inside the function, if you want the function to be able to modify the value of a formal parameter, and you want the changes to be valid after the function ends, then you need to define the formal parameter as the input and output form parameter.

At the beginning of the formal parameter definition a inout keyword can define a formal parameter for an input and output. The form parameter of the input and output has a value which can be input to the function, and the function can change it. You can also output to the outside of the function to replace the original value.

// input and output form parameters Func swaptwoints (_ A:inout int, _ b:inout int) {    = a    = b    =ten
   
    11
    Swap (&c, &
    B); c
    //
    b
    //
    
   
function type

Each function has a specific function type that consists of the form parameter type return type.

Func addtwoints (a:int,b:int), int{    return A +- Int {    return A * B}

The chestnut above defines two simple mathematical functions addtwoints and multiplytwoints. These two functions each pass in two int values, returning an int value, which is the result of the function being mathematically computed.

Both of these functions are of type int, int. Also read as:
"A function type with two formal parameters, all of which are of type int and return a value of type int. ”

func Printhelloworld () {    print ("Hello,world")}

The type of this function is (), void, or "a function without formal arguments, returning void." ”

Using function types

You can use the function type just as you would with other types in Swift. For example, you can define a function type for a constant or variable, and assign a corresponding function to the variable.

var mathfunction: (int,int)->int = addtwoints

"Defines a variable called mathfunction, whose type is ' a function that accepts two int values and returns an int value. ' Point this new variable to the Addtwoints function. ”
This addtwoints (_:_:) function has the same type as the Mathfunction function, so this assignment can be checked by the type of Swift.

Mathfunction (3,4)
function type as return type
Func Stepforward (Input:int)int{returnInput-1}func Stepbackward (input:int)-Int {returnInput +1}func chosestepfunction (backwards:bool)(INT)Int {returnBackwards?Stepforward:stepbackward}var CurrentValue=3Let Movenearertozero= Chosestepfunction (Backwards:currentvalue >0) whileCurrentValue! =0{CurrentValue=Movenearertozero (currentvalue)}
inline functions

All of the functions described above are global functions that are defined in the global scope. You can also define another function inside the function, which is the inline function.

Inline functions are hidden externally by default, but they can still be called by the function that wraps them. The function of the parcel can also return an inline function within his interior to be used in a different scope.

Func choosestepfunction (Backward:bool), (INT)(Int) {func stepforward (input:int)-int{returnInput +1} func Stepbackward (input:int)-Int {returnInput-1    }    returnBackward?Stepbackward:stepforward}var CurrentValue= -4Let Movenearertozero= Choosestepfunction (Backward:currentvalue >0) whileCurrentValue! =0{CurrentValue=Movenearertozero (currentvalue)}

The above is the part of Swift about the function, the comparison of the basis, later meet the complex will come back to update.

Swift Learning Notes (functions)

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.