Swift syntax basics 3 (functions, closures), swift syntax
Swift syntax basics 3 (functions, closures)
Function:
- A function is an independent code block used to complete a specific task. You give a function a proper name to identify what the function is doing. When the function needs to be executed, the name will be used to "call" the function.
- Format:
- Func function name (Parameter Name: parameter type, parameter name: parameter type...)-> function return value {function implementation part}
No parameter, no return value
Func say ()-> Void {print ("hello")} say () func say1 ()-> () {print ("hello")} say1 () // recommended func say2 () {print ("hello")} say2 ()
Parameters with no return values
Internal/external parameters
- Internal parameters: Before Swift2.0, internal parameters are used by default.
- Beginning with Swift2.0, the second parameter name is used as an external parameter by default.
- If external parameters are not explicitly specified, the system uses the parameter name as an external parameter from the second parameter by default.
- External parameters can only be used externally, but not internally. Internal parameters can only be used internally.
- Ignore external parameters: Add _
// Before Swift2.0, the parameter name starting with the second parameter is not used as an external parameter by default. You must manually specify 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 Parameter (Default Parameter Values)
- Format: func method (parameter: Int = 0 ){}
- When the default value is defined, you can ignore this parameter when calling this function.
- The default parameters of other languages must be written at the end, and Swift can be written at any location.
Note:
- Put parameters with default values at the end of the function parameter list. This ensures that the order of non-default parameters is consistent during function calling and makes the same function clearer when it is lowered in different situations.
Func sum2 (I: Int, j: Int = 10) {print (I + j)} // sum2 (10, j: 20) sum2 (10) // This is not recommended. It is best to write the default parameter in the final func sum3 (I: Int = 20, j: Int) {print (I + j )}
Constant Parameters and Variable Parameters (Constant and Variable Parameters)
- Function parameters are constants by default and cannot be modified within the function.
- To modify a parameter in a function, you must add var before the parameter.
Note:
- Modifications to the variable parameters disappear after the function call, and are invisible to the function in vitro. Variable parameters only exist in the life cycle of function calls.
Func sum4 (let I: Int, let j: Int) {print (I + j)} sum4 (10, j: 20) var num1 = 10var num2 = 20 // func swap (value1: Int, value2: Int) {// let temp = value1 // value1 = value2 // value2 = temp //} // Note: local variables are operated and func swap1 (var value1: int, var value2: Int) {print ("before Interaction: value1 = \ (value1), value2 = \ (value2 )") let temp = value1 value1 = value2 value2 = temp print ("after interaction: value1 = \ (value1), value2 = \ (value2)")} swap1 (num1, value2: num2) print (num1) print (num2)
Input and Output Parameters (In-Out Parameters)
- Variable parameters, as described above, can only be changed in the function body. If you want a function to modify the value of a parameter, and you want these modifications to still exist after the function call ends, this parameter should be defined as an input/output parameter (In-Out Parameters)
- When defining an input/output parameter, add the inout keyword before the Parameter definition.
Note:
- Input and Output Parameters cannot have default values, and variable parameters cannot be marked with inout. If you use inout to mark a parameter, this parameter cannot be marked by var or let.
Func swap2 (inout value1: Int, inout value2: Int) {print ("before Interaction: value1 = \ (value1), value2 = \ (value2 )") let temp = value1 value1 = value2 value2 = temp print ("after interaction: value1 = \ (value1), value2 = \ (value2)")} swap2 (& num1, value2: & num2) print (num1) print (num2)
Variadic Parameters)
- One Variable Parameter can receive zero or multiple values.
- If there is no Variable Parameter Function and the number of parameters of the function is unknown, you can only write multiple methods or change the function parameter to a set.
- Format: func method (parameter: Int ...){}
- Variable parameters can be used as an array in a function.
Note:
- A function can have at most one variable parameter.
- Variable parameters can only be data of the same type
- The data type must be specified for the variable parameter.
- If a function has one or more parameters with default values and one variable parameter, put the variable parameter at the end of the parameter table.
Func sum5 (numbers: Int ...) {// print (numbers) var sum = 0 for number in numbers {sum + = number} print (sum)} sum5 (1, 2, 3) // not recommended, like the default value, it is best to write the variable parameter in the final func sum6 (numbers: Int ..., var sum: Int) {// print (numbers) for number in numbers {sum + = number} print (sum)} sum6 (1, 2, 3, sum: 0) // recommended func sum7 (var sum: Int = 100, numbers: Int ...) {// print (numbers) for number in numbers {sum + = number} print (sum)} sum7 (numbers: 1, 2, 3) // one function can only have one variable parameter // func sum8 (numbers: Int ..., values: Int ...) {// print (numbers) // print (values) /// the returned value func sum8 (I: Int, j: Int) is returned for a parameter) -> Int {return I + j} let result = sum8 (10, j: 20) print (result)
Closure
Closure
// Normal method loadData ({()-> () in print ("executed")}) * // other method of closure // 1. if the closure is the last parameter of the function, you can write the closure after calling the function (). // this method is called "trailing closure" loadData ("123 "){() -> () in print ("executed")} // 2. if the function only receives one parameter and this parameter is a closure, the method of calling the function () can be omitted. This is called "trailing closure" loadData {()-> () in print ("executed ")}
Func loadData (since_id: String, finished: ()-> Void {dispatch_async (dispatch_get_global_queue (0, 0 )){() -> Void in print ("subthread time-consuming operation \ (NSThread. currentThread () ") dispatch_async (dispatch_get_main_queue (), {()-> Void in print (" the main thread updates the UI \ (NSThread. currentThread () ") finished ()}/* func loadData (finished: ()-> Void {dispatch_async (dispatch_get_global_queue (0, 0 )) {()-> Void in print ("sub-thread time-consuming operation \ (NSThread. currentThread () ") dispatch_async (dispatch_get_main_queue (), {()-> Void in print (" the main thread updates the UI \ (NSThread. currentThread () ") finished ()})}}
Circular reference of closures
// Weak var weakSelf = self // unowned var weakSelf = self callBack = {[unowned self, weak btn = self. button] ()-> () in // self. 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 ("subthread time-consuming operation \ (NSThread. currentThread () ") dispatch_async (dispatch_get_main_queue (), {()-> Void in print (" the main thread updates the UI \ (NSThread. currentThread () ") finished ()})}}
- Destructor
- The Destructor only applies to the class type. Before a class instance is released, the Destructor is called immediately.
- Similar to the dealloc method in OC
- The Destructor is automatically called before the instance is released. You cannot actively call the destructor
- In general, when using your own resources, perform some extra cleaning in the destructor.
For example, if you create a custom class to open a file and write some data, you may need to manually close the file before the class instance is released.
deinit { print("88") }
End