Introduction to Swift Syntax Basics three (functions, closures)

Source: Internet
Author: User
Tags closure

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

    1. Can be written as->void
    2. can be written as ()
    3. Can omit
    4. 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

    • Closures are self-contained function code blocks that can be passed and used in code. Closures in Swift are similar to the code blocks in C and objective-c (blocks) and anonymous functions in other programming languages
    • Closures can capture and store references to any constants and variables in the context in which they are located. This is called closed merge wrapped with these constants and variables, commonly known as closures
    • Closures are used like blocks to hold a piece of code and act as a callback to perform time-consuming operations
    • Closure format: The In keyword is designed to facilitate distinguishing between return values and executing statements
       {     (形参列表) -> 返回值类型     in     执行语句 }
        // 正常写法        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
  • Closed Loop Strong reference
  • Block

    • Closures are like blocks, which are prepared in advance and executed when needed
    • The block will strongly reference the external variable, ensuring that the variable is still in the execution code
    • You must be very careful when you use self in a block. Close the bag
    • Closures are also strong references to external variables, which are guaranteed when the code is executed.
    • If you assign a closure to a property of a class instance, and the closure captures the instance by accessing the instance or its members, you will create a cyclic strong reference between the closure and the instance
    • Swift development can not write self, do not write self, see Self to think of closures
  • How to resolve circular references in OC

    • __weak typeof (self) weakself = self;
    • Feature: The variable is automatically assigned nil after the object is released
    • __unsafe_unretained typeof (self) weakself = self;
    • Feature: The object is not automatically assigned nil after it is released, pointing to an abandoned storage space
  • How to resolve circular references in Swift

    • weak var weakself = self
    • Weak is equivalent to __weak in OC, and the variable is automatically assigned to nil when the object is released as OC
    • So the variable modified by weak is an optional type

    • unowned var weakself = self

    • unowned equivalent to __unsafe_unretained in OC, like OC, the object does not automatically assign a variable to nil after it is released
    • So a variable that is unowned modified is not an optional type.

      Note: weak and unowned can only decorate object types, because only object types have reference counts

  • Application Scenarios:

    • When to use weak?
      • Use weak when the saved object is likely to be released early
    • When to use unowned?
      • Use unowned when the saved object is not released in advance when it is used
  • Capture List

    • You can 调用 specify a capture list in front of the formal parameter list by [] When you close the package, telling the system how to handle the specified values
        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)

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.