by travisgriggs · 7y ago · 0 comments
I really like swift, but there are times when I feel I need a magic decoder to figure out which edge cases apply. My biggest frustration is that something like this
for view in self.subviews { view in
...
return something
}
Is very different from the naively similiar self.subviews.forEach { view in
...
return something
}
I just wish closures were a more first class part of the language like they were in Smalltalk. If language written in 1980 could use closures/lambdas all the way down even for things like if/else, and keep the deception pretty complete, I don’t understand why swift can’t do similiar. func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil)
It is perfectly valid to call this function using a trailing closure for the latter argument, i.e. animate(withDuration: 0.5, animations: { ... }) {
// handle completion here
}
rendering the `completion` parameter label obsolete and giving no clear visual indication that the trailing closure is a completion handler.Again, I strongly dislike the visual similarity to control flow statements.
[1]: https://www.natashatherobot.com/swift-trailing-closure-synta...
Functions are first class types and values in Swift. Both named functions and anonymous functions can be used as values and can capture values from outer scopes. What’s not first class?
> If language written in 1980 could use closures/lambdas all the way down even for things like if/else, and keep the deception pretty complete, I don’t understand why swift can’t do similiar.
Smalltalk’s approach of using higher order functions for all control structures is more uniform in some ways but is not inherently superior. Swift has statements that perform non-local control transfer (break, continue, return) and designing those to work with closures (presumably only non-escaping closures) would be tricky. Also Swift ‘if’ and ‘switch’ statements can perform pattern matching and bind variables in various complex ways, so again it’s not clear if completely unifying all this with anonymous closure syntax would produce something that is simpler overall than just special casing conditionals and loops in the statement syntax.
for i=0;i<10;i++ { setTimeout(() => console.log(i), 100); }
and you get 10 calls logging "9". (most languages I've touched do this, JS just makes it worse since `var x` in the loop will not fix it)The second won't do that, since the "view" var isn't "mutated" between calls.
1) view is immutable in both cases
2) GGP is returning in a void block so both sets of code will fail
3) there is really no difference except iteration vs function calls as far as I can tell, you can iterate arrays and use higher order functions built into arrays... which seems normal
4) you can only access the index in (1) by calling .enumerated() I suppose.