[swift-evolution] Setter methods for vars

Austin Feight austin at chexology.com
Tue Jun 28 13:18:19 CDT 2016


I propose adding setter methods to vars, which could look something like
this: `ApiClient().fetchUsers().then(#set(users))`

Initially I thought it should work like this:
but to accomplish a line of code that flows grammatically, I believe
putting "set" where it would naturally fall if the code was being read as a
sentence is more Swifty.


The following code makes me smile:


It exemplifies the beauty of Swift. First-class functions make this line of
code read very well. Consider some alternatives:

1. ApiClient().fetchUsers().then { displayUsers($0) }
2. ApiClient().fetchUsers().then { users in displayUsers(users) }
3. ApiClient().fetchUsers().then { (users: [User]) in displayUsers(users) }

Using the lessons learned from Swift API Design Guidelines (WWDC 2016
Session 403) having an emphasis on clarity, my analysis of the alternatives

1. $0 adds no additional information as to the type or explanation of what
the argument is, thus adding nothing to the line of code for clarity, and
therefore should be omitted
2. adding "users" also adds nothing to the clarity of the code. The
function, properly, contains the information necessary to reason about the
argument it takes and what it does, and therefore adding "users" is
3. Not only is "users" redundant, but also is the explicit type label. The
`displayUsers` method will only accept one type of argument, so we're
duplicating information that the compiler (and autocomplete) already gives

With this I conclude that `ApiClient().fetchUsers().then(displayUsers)` is
the Swiftiest option.
I want to extend this same logic to when I find myself writing code like

ApiClient().fetchUsers().then { users in
  self.users = users

or alternatively, because "users" is likely redundant information again,

ApiClient().fetchUsers().then { self.users = $0 }

Personally I steer clear of `$0` as much as possible, because I very rarely
feel that it provides the information necessary for code clarity. But
beyond that, this code no longer reads as nicely as the code we had before.

Whereas `ApiClient().fetchUsers().then(displayUsers)` flows nicely as a
sentence and reads grammatically, `ApiClient().fetchUsers().then {
self.users = $0 }` no longer does.

I think this feature could have a simple implementation where the compiler
replaces `#set(X)` with `{ X = $0 }`, and I believe it would go a long way
with respect to code clarity, especially when X is something longer like

Looking forward to hearing thoughts from the community,

*Austin Feight*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160628/dab7496b/attachment.html>

More information about the swift-evolution mailing list