I have a question about Swift's closure-like description.

Asked 2 years ago, Updated 2 years ago, 31 views

(Question 1)
Is the writing method in capture (a) and (b) below closed?

I think the closure is as follows, and I think (a) will be a closure, but
(b)Does that mean that is not the case?

var hogeHoge={(parameters)->return type in
    statements
}

(Question 2)
If you look at it in Playground, (a), (b) have different results as shown in the capture.
What is the grammatical difference between the parentheses at the end?
(a)I think ( ) of (b) is omitted.

Thank you for your cooperation.

Capture Playground

swift

2022-09-30 16:52

2 Answers

(As much as possible, textual questions should not be pasted on the image.If you can reproduce the event simply by copying it to the Playground on the part of the respondent, you are more likely to get an answer.This time, it's short, so I directly hit it again.)

I think it's easier to understand if you answer them all together.

(Question 1)
Is the writing method in Capture (a), (b) below a closure?
(Question 2)
If you look at it in Playground, (a), (b) have different results as shown in the capture.
What is the grammatical difference between whether or not there is parentheses at the end?

(a) The {return10} portion is the closure, and the hoge is substituted for the closure.
(b) The {return10} part is the closure, and () indicates that the closure is called, and foo replaces the result of calling the closure.

I think (a) omitted (b) of (b)

Be sure to distinguish between substituting the closure itself for variables, passing it to method parameters, and calling the closure.Swift cannot omit () when calling functions that do not take parameters (including methods and closures), so it would be very dangerous if the meaning of "() was omitted."


2022-09-30 16:52

b calls the function (closure) defined for the last ().
The result is a constant value of 10.

You may not have to worry about it now, but
Neither is strictly closed.
I'm just defining and using functions.

Therefore, the answers are as follows:

Is the writing method in capture (a) and (b) below closed?

Neither is strictly a closure.a defines a function.
b is running immediately after defining the function.

What is the grammatical difference between whether or not there is parentheses at the end?

With parentheses, the previous function is called and executed.

For information on why the capture example is not a closure, Wikipedia will quote the following instead.

A variable other than an argument is resolved in a self-defined environment (static scope) rather than in a runtime environment.


2022-09-30 16:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.