Why declare a closure as a variable?

Hello, total Swift beginner here...

What is the purpose of declaring a closure as a variable as opposed to a constant?

Any insight would be appreciated. Thank you kindly.

If difficultyRating is never re-assigned, then the answer is simple: there is no benefit. In some contexts, the compiler would raise a warning for this.

1 Like

So that you can modify it, which is the same reason why you would declare any other property as a variable.

2 Likes

Thanks. I suppose I'm not sure how or why I would modify a closure as yet.

Thank you.

It's not about modifying the closure itself or not (you can't), it's about whether or not you can reassign a value to the difficultyRating a second time.

This is just like with classes, var isn't necessary for making modifications to the objects pointed to by the variable, but it is necessary if you like to assign other objects the variable.

5 Likes

Thanks very much Alexander.

Terms of Service

Privacy Policy

Cookie Policy