126 points · by ingve · 6y ago · 135 comments
This time around it's callAsFunction. Yeah, pretty easy to understand in their toy example. When it's deployed IRL with a ton of other things going on, and larger distances between declaration and usage, it looks like a nightmare.
I love writing Swift for myself, but I write it in a pretty boring way. When I have to work with people who get creative and clever, it's awful.
Not relevant to most situations, but I'll just add that this also makes it extremely difficult to teach a language.
I have taught Ruby -- a language with quite a sweet tooth -- for almost twenty years, and I feel like it gets worse and worse every year. Students run off to look at example code online (as they should), but discover that I have been teaching them what seems to them like a different language.
It really leaves me with no choice but to spend a lot of time in lectures saying, "You can do it this way . . . or this way . . . or this way . . . and by the way, these are all semantically equivalent."
Pretend you know nothing about a language, why would you assume .map { $0.thing } and .map(\.thing) are even remotely similar?
I'm not sure how invested your team is in Swift, but since we do nothing but Typescript, the investment in time (2-3 days for one the lead engineer) tweaking the linter has more than paid off ten-fold in the months since.
This is one of my concerns with adopting Typescript in my team. Would you please share more info about the kinds of things you prohibit, and why you chose them?
I generally love syntax sugar that makes me more productive, cuts out boilerplate, and reduces cognitive overhead... but for me, callAsFunction and even maybe Key Path Expressions as Functions are going to ADD cognitive overhead.
I suppose if I only used Swift, and used it every day, they would be OK, but otherwise it's just more fiddly things that deviate from existing patterns.
Think most agree expressive syntax while minimizing boilerplate is at times going to require sugar. It's interesting you bring cognitive load into the question – perhaps I come at it more from an architectural light than PL fans, but that load seems largely correlated with one's purposes and patterns in using the language.
On that front, Swift has lofty and broad goals (including DSLs), but that surface area doesn't make the language worse. To take your other example, KeyPath Functions don't change anything about KeyPaths; the concept is and remains no different than anywhere else it's implemented (whether in Swift or in another language). Beginners can still use the concept, skill comes with understanding how/why it works, and mastery comes with knowing when/how to use it simply.
If Swift achieves said goals, one needn't be able to understand the last mile of any specific domain where it's used as a language. But it'll be quicker and easier than coming from another language, and the sugar will still be as sweet.
Frankly, it's misleading/silly for me to complain about Swift additions since I don't have the opportunity to write much of it, and primarily only read/consume it with Obj-C code. (I have no choice in this matter.) Basically the language already has a high cognitive load for me, so of course any additions feel burdonsome.
Also, I'm unfamiliar with using KeyPaths like that, so I'm clearly way off on my reaction to them.
The general goals of Swift make me want to learn it better and use it, honestly.
I could (and do) say the same thing about Perl.
I can already imagine cases where callAsFunction() would be handy. For example, having a viewTemplate = SomeView(customization: etc) then creating copies via viewTemplate()
I could create button templates then make slightly different copies of those templates without having to subclass Button or attaching .copy()
SwiftUI is all about succinctness.
Chances also are that it is inspired by python’s callable (https://en.wikipedia.org/wiki/Callable_object#In_Python), which, as far as I know, people don’t complain about much.
I have seen something similar before in Python where a class implements __call__, but I have never needed to use it.
Isn't this more like a problem you have with the team, rather than a problem with the language itself?
That's the same reply that people have to "C++ has too large a surface area". Granted, Swift isn't quite at C++ levels of complexity yet, but ideally, I shouldn't have to cordon off sections of the language I'm using just so my team can stay sane.
One thing I wish Swift had was an easy way to add more generic functionality. For example, if I want to add drop(), dropWhile(), take(), takeWhile(),... there’s no nice way to extend Array
[1,2,3].take(2)
[“a”,”b”,”c”].take(2)
Btw, I’m working a Swift Cookbook for anyone who quickly wants to come up to speed on Swift. All open source. Feel free to comment or commit.That’s why I provided two examples containing different types to illustrate what I meant.
I don’t believe you can add a generic function to the array to handle this.
In another repo, I’ve used the FloatingPoint protocol with some luck. However, this should also work with Int’s, for instance:
extension Array where Element: FloatingPoint {
var sum: Element {
self.reduce(0, +)
}
}
https://github.com/melling/data-science-from-scratch-swift/b...The rest look like they aren't worth complicating the language over. Consider:
map(\.name)
Isn't really more concise than map { $0.name }
There's one more character and the conventions for whitespace are different. Both require that you know special Swift syntax sugar features, but at least the second one is more generally useful. All we get here is a virtually identical way to do the same thing but with alternate arbitrarily different syntax.And what's better... this?
struct Dice {
var lowerBound: Int
var upperBound: Int
func callAsFunction() -> Int {
(lowerBound...upperBound).randomElement()!
}
}
let d6 = Dice(lowerBound: 1, upperBound: 6)
let roll1 = d6()
or this? struct Dice {
var lowerBound: Int
var upperBound: Int
func roll() -> Int {
(lowerBound...upperBound).randomElement()!
}
}
let d6 = Dice(lowerBound: 1, upperBound: 6)
let roll1 = d6.roll()
callAsFunction() makes it a little harder to relate the calling code to the implementing code -- you've got to internalize the new syntax-sugar rule -- and the calling code gets a little less clear in some cases.Default arguments to subscript functions is probably OK. It's better if all kinds of function have the same capabilities.
It's for Swift for TensorFlow's integration with Python, in which a bridged Python object can be called as a function. Functions are, of course, objects in Python, so that makes sense, but it would be a pain to have to call fn.call(bar) instead of fn(bar) when fn is a reference to a python object that is a function in its runtime.
It's also used in TensorFlow models, in which callAsFunction() is usually implemented as passing the model's input through all the defined layers in it.
This makes it easy to treat models as if they were functions, which they mathematically are, unlike Dice.
Example:
struct MLP: Layer {
var layer1 = Dense<Float>(inputSize: 2, outputSize: 10, activation: relu)
var layer2 = Dense<Float>(inputSize: 10, outputSize: 1, activation: relu)
@differentiable
func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> {
let h0 = layer1(input).withDerivative { print("∂L/∂layer1 =", $0) }
return layer2(h0)
}
}
(from: https://www.tensorflow.org/swift/tutorials/custom_differenti... )It's a bad example enabled by a bad language feature. Just you wait until answers on stack overflow, sample code, and open source libs are littered with these "bad examples".
Meanwhile, this example is terrible. There is no real need for callAsFunction in your example when you could have added a simple named function on the object to do so. Better yet, you could define a protocol and make sure your layer conforms to said protocol.
Any feature, no matter how good, can be misused. Pointing that out about a specific feature isn't interesting, because it is true of every feature. And the absence of nearly any feature can be worked around, as ultimately all these features compile down to machine code, which doesn't have most features of a high-level language, so the existence of a workaround is also not a very compelling argument.
“Callability” not being restricted to functions (closures or not) can often be convenient, especially when that use is colloquial (eg closure where symbols and collections are callable), and obviate unnecessary boilerplate.
Functions are objects in many langages. Python’s specific feature is that there are callable a beyond functions. A class is a callable and a user-defined object can be one despite neither being functions.
Clojure also has that concept.
Keypaths are used in other places and useful. But they aren’t used very often, and I felt I was forgetting their syntax when I first learned Swift.
By making them useful in two areas with largely the same semantics, it helps you understand and use them in practice more.
In the end it’s all fairly subjective, but it doesn’t bother me as a relative newcomer.
This was the exact motivation. It was part of a refactoring to clean up some implementation details and resulted in a net deletion of lines of code.
func die(lowerBound: Int, upperBound: Int) -> () -> Int {
{ (lowerBound...upperBound).randomElement()! }
}
let d6 = die(lowerBound: 1, upperBound: 6)
let roll1 = d6()
so the syntax already exists.The proposal doesn't seem to have one.
https://github.com/apple/swift-evolution/blob/master/proposa...
Never underestimate peoples (often irrational) hatred for sigils, or even things that remind them of sigils.
Language designers seem to underestimate the cognitive overhead of syntax duplication.
StateStream.map { $0.subState }.compactMap(\.subObject).flatMap { $0.objectProperty }
Being correct is super frustrating.
IMO, some better alternatives, in order of personal preference:
* Give away the functionality to all types that implement only a single function.
* Require an explicit protocol conformance. I get that the language does not want features to be hidden away, but requiring a user to implement a function with a specific name and signature is literally the job of a protocol. It doesn't seem like much of a hurdle for non-beginners, who have likely been familiarized with core protocols like Sequence or Collection, to acquire a knowledge of a CallAsFunction protocol.
* Introduce a new keyword, or tag (like @implicit).
* Allow the user to unlock the functionality through a more obscure phrasing. Even something as ugly as "func ` `()" could be preferable.
> Xcode 11.4 requires a Mac running macOS Catalina
Shit.
But you're not allowed to submit apps to the stores with unofficial toolchains.
Subscript default arguments will also be really useful.
Not sure about the callAsFunction() stuff, but I'm sure people will come up with good ideas for it.
That being said, releases like this are pretty frustrating because they seem to reflect a focusing on tiny bits of sugar (can we even call them that?) instead of features that have a much more positive influence experience. Besides "better error messages" how do any of these things improve the development experience?
`map(\.name) vs map { $0.name }`. Why...?
`callAsFunction()` feels bizarre... how is `obj()` more elegant or less confusing than `obj.callAsFunction()`.
Meanwhile the Swift dev experience still has lots of annoying bugs & usability issues (though to its credit it has improved by leaps about bounds). My personal pet peeve is that sensible compiler synthesized inits[1] still have not been implemented despite requests (and proposals!) coming up again[2] and again[3] and again[4] and again[5]
Sometimes I wonder if anyone is actually asking questions like "what value is this providing to the user?". Maybe there's so many strong opinions nothing of substance can get through the approval process?
Announcements like this[6] get me excited that the language is heading in the right direction, but it'll be a lot more convincing when the a release shows that.
[1] https://github.com/apple/swift-evolution/blob/master/proposa...
[2] https://forums.swift.org/t/it-should-be-possible-to-generate...
[3] https://forums.swift.org/t/explicit-memberwise-initializers/...
[4] https://forums.swift.org/t/default-struct-initializer-intern...
[5] https://stackoverflow.com/questions/26224693/how-can-i-make-...
This article is about changes to the language. The bulk of the effort in this release went into improving the _compiler_: better error messages, faster compile times, smaller code size, and fixing bugs.
> And this will return all users who have a best friend:
should be
> And this will return all best friends of users:
`let bestFriends = users.compactMap(\.bestFriend)`
Add to it constant major releases requiring new xcode or MacOs. Suddenly all your existing App codes have to be upgraded to even release to appstore. I swear justice will one day be served Apple for abusing the high end smartphone monopoly.