Swift-func (function)

Source: Internet
Author: User
Tags pow

A function is a collection of statements organized together to perform a specific task.

Swift functions are similar to simple C functions and complex Objective C language functions. It enables us to call internal local and global parameter values through function calls. Like any other language, Swift functions follow the same steps.

    • function declaration: It tells the compiler about the name of the function, the return type, and the parameters.

    • function definition: It provides the actual body of the function.

The Swift function contains the parameter type and return type.

function definition

In the swift language, functions are defined by the "func" keyword. When a new function is defined, it may need one or several values as the function input as "parameters", it will be processed in the function body and return the value as the ' return type ' output.

Each function has a function name that describes the task that the function will perform. to use a function, you call its name function and match the function's parameter type through its input value (called a parameter). Function parameters are also referred to as "tuples".

The parameters of the function must be provided in the same order as the function argument list, and return a value after.

Grammar
Func funcname (Parameters), returntype{   Statement1   Statement2    ---   Statement N    return parameters}

e.g

Func student (name:string), String {   return  name}println (Student ("  First program")) println (student,"aboutFunctions "))

Print results

First Programabout Functions

Functions with multiple parameters

Func mult (No1:int, No2:int), Int {   return no1*no2}println (mult (2,20  )) println (mult (3))println (mult (4,))
 +  $  -

Functions can also be used to return strings, integers, and floating-point data type values as return types. To find the maximum and minimum number of the array function "LS", declare it with the Large,small integer data type.

The array is initialized to hold the integer value. The array is then processed and each value in the array is read out and written with its previous value comparison. When the value is smaller than the previous parameter stored in "small", the parameter value stored in "large" is returned by calling the function

Back up multiple parameters

Func ls (array: [INT])(Large:int, small:int) {var lar= array[0] Var sma= array[0]    forIincharray[1.. <Array.count] {ifI <SMA {SMA=i}Else ifi >lar {lar=i}}return(Lar, SMA)}let num= LS ([ +, A,-5, +,98]) println ("largest number is: \ (num.large) and smallest number is: \ (num.small)")
 is 98 is:-5

Returns a function of type Optional

Swift launches the "optional" feature to eliminate problems by introducing a security countermeasure. For example, consider that we declare the function value return type to be an integer, but what happens when the function returns a string value or any 0 value? In this case, the compiler returns an error value. "Optional" is introduced to get rid of these problems.

The optional (Optional) feature will take two forms of ' value ' and ' nil '. We'll mention ' optionals ' using the key to preserve the character "?" checks if a tuple returns a value or 0 value.

Func Minmax (array: [Int]) (Min:int, max:int)? {    ifArray.isEmpty {returnNil} var currentmin= array[0] Var Currentmax= array[0]     forValueincharray[1.. <Array.count] {ifValue <currentmin {currentmin=Value}Else ifValue >Currentmax {Currentmax=Value}} return(Currentmin, Currentmax)}iflet bounds = Minmax ([8, -6,2,109,3, in]) {println ("min is \ (bounds.min) and Max is \ (Bounds.max)")}
 is-6is109
External parameter boot name

The external parameter boot name allows you to name a function parameter to make their purpose more explicit. Name the parameters of the two function, and then call the function as follows

Func Pow (firstarg a:int, Secondarg b:int), Int {   = a   for in1 .. <b {      = res * a   }   println (res)   return  res}pow (firstarg:  5, Secondarg:3)

When we use playground to run the above program, we get the following results

125
Parameter variable type parameter

When we want to define a function with more than one quantity parameter, we can declare a parameter with a member as a "variable parameter". Parameters can be specified as mutable parameters by (...) After the parameter name.

 func vari<n> (Members:n ...) { for  i in   Members {println (i)}}vari ( 4 , 3  , 5  ) Vari ( 4.5 , 3.1 , 5.6  ) Vari (   Swift  , "   Enumerations  , "  closures  ) 
4 3 5 4.5 3.1 5.6 Swiftenumerationsclosures

function by default, consider the parameter ' constant ', where the user can also declare a parameter to a function as a variable. We have already discussed the ' let ' keyword used to declare a constant parameter, and the definition of a mutable parameter is to use the "var" keyword.

The I/o parameter provides the ability to retain parameter values in Swift, even after the value is modified by a function call. The reserved member value is declared at the start of the function parameter definition "inout" keyword.

It originates from the keyword "inout" because its value is passed ' in ' to the function and its value is accessed, and its function body is modified, and the function returns to "out" to modify the original parameter.

Because the value alone is inside, the function outside modifies the variable to pass the In-out parameter only as a parameter. Therefore, it is not necessary to declare a string, text as the In-out parameter. ' & ' before the variable name refers to the passed parameter.

Func Temp (inout a1:int, inout b1:int) {   = A1   = B1   =2   Temp (&no, &Co) println ("swapped values are \ (no), \ (CO )")
Ten 2
Nested functions

A nested function invokes an external function by calling an intrinsic function.

()  int {//Returns a function    0   , int {      =      Total   return overalldecrement//Returns a value of type int   }   return ) println (Decrem ())
-

Swift-func (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.