Introduction to Swift Syntax Basics three (functions, closures)
Function:
- A function is a separate block of code that is used to accomplish a specific task. You give a function a proper name to identify what the function does, and when the function needs to be executed, the name is used to "invoke" the function
- Format:
- Func function name (parameter name: argument type, Parameter name: argument type ...)--function return value {function implementation part}
No parameter no return value
- Can be written as->void
- can be written as ()
- Can omit
- Void. It is actually an empty tuple (tuple), without any elements that can be written ()
func say() -> Void { print("hello")}say()func say1() -> () { print("hello")}say1()// 推荐func say2() { print("hello")}say2()
There are no return values for parameters
Internal/External parameters
- Internal parameters: Swift2.0 Previously, the parameters are internal parameters by default
- Swift2.0 start, the second parameter name is used as the external parameter by default
- If an external parameter is not explicitly specified, the system defaults to the second parameter, which takes the name of the parameter as an external parameter
- External parameters can only be used externally, internal functions cannot be used, internal parameters can only be used inside functions
- Ignore external parameters: add _ before internal parameters
// Swift2.0之前, 默认是不会将第二个参数开始的参数名称作为外部参数的, 必须自己手动指定func sum(i: Int, j: Int) { print(i + j)}sum(10, j: 20)func sum1(first i: Int, second j: Int) { print(i + j)}sum1(first: 10, second: 20)
Default parameters (Parameter Values)
- Format: Func method (Parameter:int = 0) {}
- When the default value is defined, this parameter can be ignored when calling this function
- Default parameters for other languages must be written on the last side, and Swift can be written anywhere
Attention
- Place the parameter with the default value at the end of the function argument list. This guarantees that the order of the non-default arguments is consistent when the function is called, and makes the same function clearer when invoked under different circumstances.
func sum2(i: Int, j: Int = 10) { print(i + j)}//sum2(10, j: 20)sum2(10)// 不推荐这样写, 最好将默认参数写在最后func sum3(i: Int = 20, j: Int) { print(i + j)}
Constant parameters and variable parameters (Constant and Variable Parameters)
- Function arguments are constants by default and cannot be modified inside a function
- If you want to modify a parameter in a function, you must precede the argument with Var
Attention
- Modifications to variable parameters disappear after the function call ends and are not visible outside the function body. Variable arguments exist only in the life cycle of a function call
FuncSum4(Let I:int,Let J:int) {Print (i + j)}sum4 (Ten, J:20)var num1 =10var num2 =20Func swap (Value1:int, value2:int) {Let temp = value1value1 = value2//value2 = Temp//}//Note: The action is a local variable , no effect on arguments func swap1 (var value1:int, var value2:int) { print ( "before interaction: value1 = \ (value1), value2 = \ (value2) "let temp = value1 value1 = value2 value2 = temp" Span class= "hljs-built_in" >print ( "after interaction: value1 = \ (value1), value2 = \ (value2) ")}swap1 (NUM1, value2:num2) print (NUM1) Span class= "hljs-built_in" >print (num2)
Input and output parameters (In-out Parameters)
- Variable parameters, as described above, can only be changed within the function body. If you want a function that modifies the value of a parameter and wants it to persist after the function call ends, define the parameter as an input-output parameter (in-out Parameters)
- When defining an input/output parameter, add the InOut keyword before the parameter definition
Attention
- Input and output parameters cannot have default values, and mutable parameters cannot be marked with inout. If you mark a parameter with inout, this parameter cannot be marked by Var or let.
func swap2(inout value1: Int, inout value2: Int){ print("交互前: value1 = \(value1), value2 = \(value2)") let temp = value1 value1 = value2 value2 = temp print("交互后: value1 = \(value1), value2 = \(value2)")}swap2(&num1, value2: &num2)print(num1)print(num2)
Variable parameters (Variadic Parameters)
- A variable parameter can receive 0 or more values
- If there is no variable parameter function, and the number of arguments of the function is not sure then you can write more than one method or change the function parameter to a collection
- Format Func method (Parameter:int ...) {}
- Variable arguments can be used as an array in a function
Attention
- A function can have at most one variable parameter
- Arguments can only be data of the same type
- Parameter must specify data type
- If the function has one or more parameters with default values, and there is a mutable parameter, then the variable parameter is placed at the end of the parameter table.
FuncSum5(Numbers:int ...) {Print (Numbers)var sum =0For numberIn numbers {sum + = number}Print (sum)}SUM5 (1,2,3)Not recommended, as with default values, the arguments are best written in the lastFuncSum6(Numbers:int ...,var sum:int) {Print (Numbers)For numberIn numbers {sum + = number}Print (sum)}sum6 (1,2,3, Sum:0)Recommended wordingFuncSum7(var sum:int =Numbers:int ...) {Print (Numbers)For numberin numbers {sum + = number} print (sum)}sum7 (numbers: 1, 2, 3)//A function can have only one variable parameter //func sum8 (numbe Rs:int, Values:int ...) {//print (Numbers)//print (values)//}//parameter has return value func sum8(I:int, J:int), Int { return i + j} letresult = SUM8 (ten, J: )print (result)
Closed Package
Closed Package
// 正常写法 loadData ({ () -> () in print("执行了") }) */ /* // 闭包的其它写法 // 1.如果闭包是函数的最后一个参数, 那么可以把闭包写在调用函数的()后面 // 这种写法, 我们称之为 "尾随闭包" loadData("123") { () -> () in print("执行了") } // 2.如果函数只接收一个参数, 并且这个参数是闭包, 那么调用函数的()可以省略 // 这种写法, 我们称之为 "尾随闭包" loadData { () -> () in print("执行了") }
FuncLoadData(Since_id:string, finished:()())void {dispatch_async (Dispatch_get_global_queue (0, 0)) {(), void in Print (\ (Nsthread.currentthread ())") Dispatch_async ( Dispatch_get_main_queue (), {(), void in print (" main thread update UI \ (Nsthread.currentthread ()) ") Finished ()})}} /* func LoadData (finished: ()), Void {Dispatch_async (dispatch_g Et_global_queue (0, 0)) {(), Void in print ("Child thread takes time-consuming operation \ (Nsthread.currentthread ())") Dispatch_async (dispatch_get_ Main_queue (), {(), Void in print ("main thread update UI \ (Nsthread.currentthread ())") Finished ()}}}}
Circular references for closures
weak var weakself = selfunowned var weakself = self CallBack = {[unownedSelf,Weak btn =Self.button] () ()InchSelf.view.backgroundColor = Uicolor.redcolor ()WeakSelf.view.backgroundColor = Uicolor.redcolor ()Self.view.backgroundColor =Uicolor.redcolor ()print (BTN)} loaddata (callback!)} func loaddata (finished: ()-> ()) void {dispatch_async (Dispatch_get_global_queue (0, 0)" {(), void in Print (\ (Nsthread.currentthread ())") Dispatch_async ( Dispatch_get_main_queue (), {(), void in print (" main thread update UI \ (Nsthread.currentthread ()) ") Finished ()})}}
- Destructors
- Destructors are only applicable to class types, and the destructor is called immediately before an instance of a class is disposed
- Similar to the Dealloc method in OC
- A destructor is called automatically before an instance release occurs. You can't call the destructor on your own.
- In general, when you use your own resources, perform some additional cleanup in the destructor
例如,如果创建了一个自定义的类来打开一个文件,并写入一些数据,你可能需要在类实例被释放之前手动去关闭该文件
deinit { print("88") }
End
Introduction to Swift Syntax Basics three (functions, closures)