iOS Development Swift Chapter-(eight) functions (2)
First, the function type
A function type is also a type of data that consists of a formal parameter type and a return value type, in the form
return value type (List of parameter types)
1 func sum (num1:int, num2:int), Int {2 return num1 + num23}
The function type of the SUM function is (int, int), int
1 func printline () 2 {3 println ("-----------")4 }
There are 4 ways to represent the function type of the PrintLine function
(1)void , void
(2)( ) ()
(3)Void-and ()
(4)() Void
Ii. defining variables using function types
You can use function types to define variables, and you can store this type of function in the future.
1 func sum (num1:int, num2:int), Int {2 return num1 + num23}4 var fn: (int, int), int = sum5 fn (ten// back to
Because Swift has a type inference mechanism, it is also possible to write this
var fn = sum //FN After the type of the stored function must be (int, int), int
Third, function as parameter
As with other data types, functions can also function as arguments
1 func printresult (fn: (int, int),2{3 println (" Operation result is:%d", fn (NUM1, num2))4 }
The FN parameter receives a function that must return an int, with 2 arguments of type int
1Func sum (num1:int, Num2:int)Int {2 returnNUM1 +num23 }4Func minus (Num1:int, num2:int)Int {5 returnNUM1-num26 }7Printresult (SUM, -,Ten)// -8Printresult (minus, -,Ten)//Ten
Iv. functions as return values
As with other data types, functions can also function as return values
1Func gotowork () {println ("go to work") }2Func Playfootball () {println ("play football") }3Func Howtodo (Day:int), () {4 ifDay <6 {5 returngotowork6}Else {7 returnPlayfootball8 }9 }Tenvar fn = Howtodo (7) One fn () A //play football
V. Function overloading
Function overloading: function name is the same, function type is different
The following 2 functions form an overload
(1) Function name: Sum, Function type: (int, int), int
1 func sum (num1:int, num2:int), Int {2 return num1 + num23}
(2) Function name: Sum, Function type: (int, int, int), int
1 func sum (num1:int, Num2:int, Num3:int), Int {2 return NUM1 + num2 +
num3
3 }
Six, nested functions
Global Functions : Functions defined in the global scope
nested functions : Functions defined in the body of a function
code example:
1Func Howtodo (Day:int), () {2Func gotowork () {println ("go to work") }3Func Playfootball () {println ("play football") }4 ifDay <6 {5 returngotowork6}Else{returnPlayfootball}7 }8var fn = Howtodo (5)9FN ()//go to workTenGotowork ()
Note : line 10th is the wrong wording, and the scope of the nested function is limited to the inner body of the function that defines the nested function