Swift syntax basics 3 (functions, closures), swift syntax

Source: Internet
Author: User

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

  • A closure is a self-contained function code block that can be passed and used in the code. Closures in Swift are similar to code blocks (blocks) in C and Objective-C, and anonymous functions in other programming languages.
  • Closures can capture and store references to any constants and variables in their context. This is the so-called closure and enclose these constants and variables, commonly known as closures.
  • Similar to block, closure is used to save a piece of code and call back for time-consuming operations.
  • Closure format: The in keyword is used to distinguish return values from execution statements.
    {(Parameter list)-> return value type in execution statement}
// 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
  • Strong reference of closure Loops
  • Block

    • Closures are similar to blocks. Code is prepared in advance and executed as needed.
    • Block strongly references external variables to ensure that the variables are still
    • You must be very careful when using self in block.
    • The closure is also the same, it will make a strong reference to external variables, to ensure that the variables are still in
    • If you assign a closure to the attributes of a class instance and the closure captures the instance by accessing the instance or its members, you will create a circular strong reference between the closure and the instance
    • In Swift development, no self can be written without writing it. Once you see self, you will think of the closure.
  • How to solve circular references in OC

    • _ Weak typeof (self) weakSelf = self;
    • Feature: the variable is automatically assigned to nil after the object is released.
    • _ Unsafe_unretained typeof (self) weakSelf = self;
    • Feature: After an object is released, the variable is not automatically assigned as nil, pointing to an obsolete bucket.
  • How to solve circular references in Swift

    • Weak var weakSelf = self
    • Weak is equivalent to _ weak in OC. After the same object as OC is released, the variable is automatically assigned as nil.
    • Therefore, variables modified by weak are optional.

    • Unowned var weakSelf = self

    • Unowned is equivalent to _ unsafe_unretained in OC. Like OC, the variable is not automatically assigned to nil after the object is released.
    • So the variable modified by unowned is not of the optional type.

      Note: weak and unowned can only modify the object type, because only the object type has reference count.

  • Application scenarios:

    • When to use weak
      • When the saved object may be released in advance, weak is used.
    • When to use unowned
      • Unowned is used when the saved object is not released in advance.
  • Capture list

    • You canCall[] Specifies the capture list before the form parameter list when the closure is used to tell the system how to process the specified values.
// 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

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.