What are the differences between functions and methods in Swift?

后端 未结 6 1726
遇见更好的自我
遇见更好的自我 2020-12-07 13:58

I always thought functions and methods were the same, until I was learning Swift through the \"Swift Programming Language\" eBook. I found out that I cannot use greet(

6条回答
  •  天涯浪人
    2020-12-07 14:20

    functional principle as a part of functional language

    function is a first-class type (first-class citizen) in Swift

    • assign to a variable
    • pass as an argument
    • return

    Function

    Function is a block of code that is created for executing some task. Function consists of name, optional parameters(name, type), optional return type, body.

    func name(parameterName1: Int, parameterName2: String) -> Bool {
        //statements
        return true
    }
    

    Function type - function’s parameter type and return type

    //Function type for the sample above
    (Int, String) -> Bool
    

    Method

    Method - is a function which is associated with a type - class, structure, enum [About]:

    Instance method - method which belongs to instance

    MyClass().foo()
    

    Type method - method which belongs to type itself. class or static is used[About]

    MyClass.foo()
    

    Closure

    Closure - is a block of functionality. It is a function which supports capturing concept. It is similar to block in Objective-C. Also you can find that Closure is a Lambda in functionality world but lambda just a no-name function while Closure make a copies of non-local variable

    Closure in Swift has three next forms:

    • global function(with name, without capturing) - is a function that is declared in a global scope(out of class scope). Usually it is defined as a first level of .swift file and does not have a big memory food print
    • nested function(with name, with capturing enclosing function variables) - function inside other function
    • closure expression(without name, with capturing enclosing context)
    { () ->  in
          //body
    }
    

    [non-escaping vs @escaping closure]
    [@autoclosure]

提交回复
热议问题