Swift Learning Note 6

Source: Internet
Author: User
Tags define function

Want to have a life of both length and thickness

How many people can be in the dazzling world, the rational District response?

How many people can hold on to one thing for 10 years?

Want to walk in front, need to choose wisely and stick to perseverance, also need wisdom and efficient self-management!

Vi. functions and closures

function: a piece of code that performs a specific task

The purpose is to reuse, or to nest.

closures: anonymous functions, which can be used as expressions, function arguments, function return values, to make the program more concise.

declaring function func

3 ways to declare without a return value

1, omitted, return value type

2, () empty

3,->void

Who calls the function, who is responsible for assigning parameters to the parameter.

Func Max (X:int,y:int)->int

{

var z = x>y?x:y

Return Z

}

Func sayhi (name:string)->string

{

Return "\ (name), Hello! "

}

Call

var a = 6, b=5

var result = Max (A, B)

println (Sayhi ("Renhairui"))

actual combat : Defines a function that returns the specified double numeric integer part and 2-bit fractional fraction

Func Divide (num:double)-(string,string)

{

var zheng = Int64 (num)

var Xiao = round ((num-double (Zheng)) *100)

Return ("\ (Zheng)", "\ (Xiao)")

}

Call

var test = divide (123.456)

println ("Integer: \ (test.0), decimal: \ (test.1)")

Find the maximum and minimum values in the array

Func getmaxandmin (Nums:[int]), (Max:int,min:int)

{
var max = Nums[0],min = Nums[0]

For num in Nums

{

If Num>max {

max = num

}

If Num <min{

min = num

}

}

Return (Max,min)

}

Call

var nums = [20,30,5,89,100,2,6,-1]

var result = Getmaxandmin (nums)

println ("Maximum value is: \ (result.max), minimum value: \ (result.min)")

recursive function : calls itself in a function, implicitly loops, repeats a piece of code

Actual combat known quantity column f (0) = 1,f (1) = 4,f (n+2) = 2*f (n+1) +f (n)

FUNC fn (n:int)->int

{
if n = = 0{

Return 1

}else if n ==1{

Return 4

}else{

Return 2*fn (n-1) +FN (n-2)

}

}

recursion is very useful to traverse all files under a path, and the depth is unknown.

External formal parameters

Func Girth (#width:D ouble, #height:D ouble)->double

{

Return Double (2) * (Width+height)

}

Call

println (Girth (width:12,height:22.5))

Formal parameter Default value

#height:D ouble = 20.3

println (Girth (WIDTH:12))

Remove external parameter names for default parameter parameters

_ Height:double = 20.3

deformable parameter, placed at the end of the parameter table

Func Test (a:int,books:string ...)

{

For temp in books

{

println (temp)

}

println (a)

}

Test (3, "Swift", "Renhairui", "OK")

variable parameter func girth (var #width:D ouble, #height:D ouble)->double

{

width = (width + height)

return width

}

Avoid redefining new variables in the function body

Call

var w = 3.2

println (Girth (width:w,height:12.9))

println (W)//3.2

InOut Formal parameters

The function body can modify the value of the parameter

Func swap (inout a:int,inout b:int)

{

Let TMP = a

A = b

b = Temp

}

& Assign a value to a parameter.

Call

var a = 6, b= 9

Swap (&A,&B)

The exchange has been realized!

Essence: Forces the passing of the variable pointer.

Whether a parameter of a value type or a parameter of a reference type, Swift simply passes a copy of the parameter into the function, and the value type argument is passed--a copy of the value itself

The reference type parameter is passed--and the referenced copy

function type

var myfun: (int,int)->int// type Yes (int,int)->int

It is common to copy a function to the same variable type.

The formal parameter of the function type is the function, the command mode, when the function is called!

function type can be a return value type

Actual combat

Func Square (Val:int)->int

{

Return Val * val

}

Func cube (val:int)->int

{

Return val* Val *val

}

Calculate factorial

Func factorial (val:int)->int

{

var result = 1

For index in 2...val

{

Result *=index

}

return result

}

Define function: Return value type (INT)->int

Func Getmathfunc (#type: String)--(INT)->int

{

Switch (type)

{

Case "Sqsuare":

Return Square

Case "Cube":

Return cube

Defalut:

return factorial

}

}

Call

var mathfunc = Getmathfunc (tpye: "Cube")

Output 125

println (Mathfunc (5))

Mathfunc = Getmathfunc (type: "Other")

println (Mathfunc (5))//120

function overloads multiple functions with the same name, only the parameter table, the return value type is different

Closed Package

1. No Func no function name

2. Use in keyword (can be omitted)

3, the first curly brace, moved to the formal parameter list before the parentheses

4. Omit return

5. Omitting parameter names

6. The parameter

var square: (Int)->int = {$0*$1}

println (Square (5))

25

trailing closure trailing closure if the last parameter of the calling function is a closure, the {} is put in the last

SomeFunc (20,{}) this--and SomeFunc (20) {}

Func map (var #data: [int], #fn:(Int)->int)->[int]

{

For var i= 0, Len = data.count;i<len:i++

{

Data[i] = fn (Data[i])

}

Return data

}

var Dataarr = [3,4,6,5,7]

var rvt1 = map (Data:dataarr) {$0*$0}//COMPUTE element squared

var rvt2 = map (Data:dataarr) {$0*$0*$0}//COMPUTE element cubic

Calculate element factorial cannot omit return

var rvt3 = map (Data:dataarr) {
var result = 1

For index in 2...$0

{

Result * = Index

}

return result
}

capture : Closures can access or modify variables and constants in the context (only access cannot be modified)

It doesn't matter if the scope doesn't exist.

Commonly used in nested functions

Func Makearray (ele:string) ()->[string]

{

var arr:[string]=[]

Func addelement ()->[string]

{
arr. Append (ele)

return arr

}

}

In the upper code arr, Ele captures the variables in the context, and each closure holds a copy of the variable it captures

Call

Let Addbody = Makearray ("Renhairui")

println (Addbody)//[Renhairui]

println (addbody)//[renhairui,renhairui]

Let Addother = Makearray ("Monkey King")

println (Addother)//[Sun Wukong]

println (Addother)//[Monkey King, Monkey King]

The output is two monkey King

closures are reference types , so when you copy a closure to two reference variables, the program does not copy them, so they all point to the same closure

Let addtest = Addother

println (addtest)//[Monkey King, Monkey King, Monkey King]

println (addtest)//[Monkey King, Monkey King, Monkey King, Monkey King]

Swift Learning Note 6

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.