3 ms·
Objective-C does it differently by default: int x = 0; void (^block)(void) = ^{ NSLog(@"%d", x); }; x++; block(); This will log 0, not 1. If y
by mikeash 11y ago
Objective-C does it differently by default:
int x = 0;
void (^block)(void) = ^{ NSLog(@"%d", x); };
x++;
block();
This will log 0, not 1. If you want to capture by reference rather than by value, you add __block to the declaration of x.
For a lot of people coming to Swift from Objective-C, this is a surprising change, especially if Objective-C was their first language with closures.
- qwertyuiop924 11y agoThat's a block, not a closure. It's still an anonymous function, but the semantics are slightly odd, and derived from Smalltalk, probably altered some.
- mikeash 11y ago"Blocks" is what Objective-C calls closures. A closure is just a function that captures ("closes over") the surrounding scope. Edit: strictly speaking, the construct here is an anonymous function. Objective-C calls them "blocks" and Swift calls them "unnamed closures" or "closure expressions." Both are, or at least can be, closures. (I'm not sure if the term "closure" can be used to refer to a function that could refer to variables in the enclosing scope but doesn't. Probably not.)
- qwertyuiop924 11y agoWhat you seem to be calling a closure refers to a lambda in a lexically scoped language. Particularly when they refer to free variables. Blocks are in fact lambdas, or at least closures. I was wrong in the above. In some early versions of smalltalk, blocks had some odd semantics that made them different, but this is no longer true. However, judging by the Objective-C example above, Objective-C blocks don't create true closures, as a true closure would have the semantics of the Swift code from the article.
- tarentel 11y agoThis is only surprising because of the ambiguity of value types in certain cases in Swift. If you passed it to a function and mutated it then it would work as your example. I'm still not sure why they made it work this way for closures. Using reference types closures and blocks are more or less the same.
- mikeash 11y agoWhat ambiguity are you referring to? It has nothing to do with value versus reference types. Reference types have the exact same difference between the two languages. In Swift, mutable variables are captured by reference by default, and in Objective-C they're copied by default. Value versus reference doesn't make a difference. For example: NSView *view = [NSButton new]; void (^block)(void) = ^{ NSLog(@"%@", view); }; view = [NSTextField new]; block(); In Objective-C, this will log an NSButton. Translate it to Swift and it will log an NSTextField. I don't think either behavior is more correct, it's just a fairly arbitrary choice. IMO it's surprising only if you've learned to expect one way because you worked in a language that does it that way, then encounter a language that does it the other way.