Câu hỏi phỏng vấn Swift
Câu hỏi

What is the difference betw...

Câu trả lời

In Swift, functions and closures are closely related concepts, but they have some key differences. Here is a detailed explanation:

Functions

  • Definition: Functions are named blocks of code that perform a specific task. They are declared using the func keyword.
  • Naming: Functions always have a name.
  • Scope: Functions can be defined globally or nested within other functions or types (e.g., classes, structs).
  • Invocation: Functions are typically invoked in the scope where they are defined.
  • Capture: Global functions do not capture values from their environment, while nested functions can capture values from their enclosing scope[3][5].

Closures

  • Definition: Closures are self-contained blocks of code that can capture and store references to variables and constants from their surrounding context. They are similar to anonymous functions, lambdas, or blocks in other programming languages.
  • Naming: Closures do not necessarily have a name. They are often used as inline, anonymous functions.
  • Scope: Closures can be defined inline within other functions or as standalone expressions. They cannot be defined globally in the same way functions can.
  • Invocation: Closures can be invoked at a different point in the code from where they are defined, making them useful for callbacks and asynchronous operations.
  • Capture: Closures capture values from their surrounding context, allowing them to "close over" those values and use them later[1][2][4][6].

Syntax Differences

  • Function Syntax:
    swift Copy
    func myFunction(param: Int) -> Int {
        return param * 2
    }
  • Closure Syntax:
    swift Copy
    let myClosure = { (param: Int) -> Int in
        return param * 2
    }

Use Ca...

senior

senior

Gợi ý câu hỏi phỏng vấn

senior

Can you rewrite this code using mutating function?

senior

What’s the difference between a static variable and a class variable?

middle

What's the difference between Self vs self ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào