Date
1 - 8 of 8
How to write better Swift
Gerriet M. Denkmann
This works (Xcode Version 8.3.2 (8E2002)):
class SomeClass { private var privateStatus: Int var status: Int { get{ return privateStatus } set(new) { if new == privateStatus {return} … do something here … privateStatus = new } } } But is this “privateStatus” really necessary? If not, how can it be avoided? Gerriet. |
|
Quincey Morris
On Jul 8, 2017, at 06:08 , Gerriet M. Denkmann <g@...> wrote:
This has been bugging me a lot lately. I don’t know a way of avoiding the need for an extra property, and if there is, I’d be glad to hear about it too. In a way, it’s harmless, but I find it clutters up a sequence of property declarations with what is basically boilerplate. I’ve been thinking about possible alternatives: 1. (Roughly) Let references to the property name inside computed getters and setters to refer to the backing store, turning a computed property back into a [sort of] stored property. 2. Put the declaration of the private property inside the real property:
The second one is functionally identical to the original code (so it doesn’t need any new compiler design), except for the scoping of the private property name. |
|
You can implement a property observer instead. Here’s an example from the Swift book:
class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) steps") } } } } —Jens |
|
bartramf@...
How about using the ‘didset’ observer?
class SomeClass
{
var status: Int {
didset(oldValue)
{
guard oldValue != status else { return }
… do something here …
}
}
} |
|
Fritz Anderson
I'm missing something, possibly because the example code is abbreviated. Is this not equivalent? var status: StatusEnum = .uninitialized { // Sorry, "magic number" literals // make my teeth itch didSet { guard status != oldValue else { return } switch status { // etc. } } } — F On Jul 8, 2017, at 12:12 PM, Quincey Morris <quinceymorris@...> wrote:
|
|
Quincey Morris
On Jul 8, 2017, at 17:15 , Jens Alfke <jens@...> wrote:
(Also to others suggesting will/didSet) That doesn’t solve Gerriet’s problem. You can’t *prevent* setting the backing store without writing an actual setter. Similarly, if you want to constrain a value (e.g. keep an Int value >= 1), you can do it in didSet, but only at the cost of two writes to the backing store (which may have side effects). |
|
Fritz Anderson
On Jul 8, 2017, at 9:05 PM, Quincey Morris <quinceymorris@...> wrote: That doesn’t solve Gerriet’s problem. You can’t *prevent* setting the backing store without writing an actual setter. Similarly, if you want to constrain a value (e.g. keep an Int value >= 1), you can do it in didSet, but only at the cost of two writes to the backing store (which may have side effects). In that case I think we've gotten deeper than whether a set handler solves Gerriet's problem. I'm beginning to think there is no other good way to express exactly what he wants to do because Swift must provide for a broader case. If you want to persist something, something has to persist it. In the hardest cases the something is probably not a variable. If you want to do something about it — the set of "something"s may be infinite — something has to do it. Entangling the two (or 1 + n) somethings may often be the best choice, so I wish there were a gentler word than "smell." --- ## Backing store vs property Your distinction between backing store and property is on-point: • "Backing store" stores state. That's all it does. It's in the name. How it does that is opaque to client code. It might be implemented through SQL or REST; it might be a good old bit-pattern instance variable. How it's done is not API. Ideally, the only requirement is that it behave-as-if. • Properties fall elsewhere in the Venn diagram. They may wrap a backing store, they may share in a dependency graph, they may have side effects… You can imagine a property having _only_ side effects, a useful thought because it's clearly an abuse of the syntax. (This horse died during the ObjC `@property` wars.) This is not a problem unique to Swift, except insofar as how the language requires you to reason about it. There's no eliminating the need to reason about it: You cannot _prevent_ the setting of some backing store without executing code. "Backing" describes a passive receptacle, if the word has any meaning at all. Controlling what goes into the receptacle isn't passive; it is the action of whatever owns it. You cite the complications in setting state if setting it has side effects. "side effect" → "not passive." You're not writing to a variable, you're executing a setter. You have to put that in the API contract just as you would for things that start with `func`. If it's important that some action _not_ have a certain side effect, that's a different execution path. Swift can't automagically predict problems that arise from sharing a backing store across the implementation of an API. --- ## In Swift TL;DR: Properties should be reserved for things that smell like access to values with no side effects. In practice there's a lot of gray. At the extreme I'd say: Property notation should express (+/-) pure functions with no parameters on get, one on set. They change or reflect state; it's safe to repeat invocations; they look like accesses to field variables in C-family `struct`s. Anything with a side effect whether relating to a property or not should be a `func`. That's the extreme. That's where I'd start. That's not convenient. It's error-prone. I'd like to ask a random-number generator `rng.byte` for the next byte in the sequence. My sanity depends on `will`|`didSet` handlers — but they have problems of their own: Does the contract freeze the dependencies, or risk surprises? (It usually does both.) Cycles? Order dependencies? Side effect invariants that can't immediately be assured, like configuring views that might not exist yet? That's not a rap on Swift. The problems are irreducible. A designer can only mitigate them. Language designers have no perfect choices. --- ## Swift properties are not variables My view of Swift's balance is that properties wrap default getters, setters, and setting handlers that you can replace,* but the language encourages you to forget.** `var nPeople: Int` looks like a C-style allocation of a bit-representable value within a `struct,` but it's syntactic sugar for the whole accessor package. Swift allows you to think a `var` is just a variable, but "`var`" is a red herring. One may disagree with where Swift strikes the balance (if it's what I say it is). A language with a different balance (maybe one that attaches some kind of [executable] validator to variable declarations) might be ingenious, but it would not be Swift. \* (The default getter/setter may optimize to POD access in-line; I argue no principle requires it.) ** (Much of what we mean when we tell each other Swift is an easy language suitable for small children is that it's such a relief after being stuck with C for twenty years. Pretty quickly you get into questions that verge on the rabbinical.) --- ## They keep telling me to append a summary The need for a backing variable isn't peculiar to Swift or to so-called "variables." You can express it however suits you, but the problem (if you see it as one) is irreducible. — F |
|
Quincey Morris
On Jul 9, 2017, at 14:53 , Fritz Anderson <anderson.fritz@...> wrote:
The problem is that Swift doesn’t have any backing stores separate from properties. As you say (if effect), backing stores are implementation details. In Swift, if a property implementation wants to control what goes into its backing store, it needs a 2nd property. That’s the complaint here, and it’s purely bureaucratic: the 2nd declaration gets more prominence than it deserves; your eye can’t skip it so easily when reading the source of the enclosing type. There’s no real *functional* difference. (Also, since I originally posted, I realized that it also gives the 2nd property more *scope* that it should have. Hiding the backing store belonging to a single property from the rest of the implementation seems like a really good idea. How many of us, in Obj-C code, have got ourselves into trouble by using instance variables and property accessors inconsistently in a class implementation?)
The side effects I was thinking of were KVO notifications. I’ve been playing with some use-cases in the last couple of weeks, and it’s really, really hard to get this right sometimes without explicit control of a backing store. Indeed there’s a larger discussion (that I’ve been having in my head) about the possible need for *two* setters, one from the “UI side” and one from the “model” side. The UI setter eventually calls the model setter, but only the model setter generates KVO notifications. Why a setter from the UI? The setter is involved on the UI side when the UI element is mutable and uses bindings. OTOH UI methods that don’t use bindings use action methods instead, and (again in the discussion in my head) I’ve been considering whether some action methods are somehow part of properties, as in “get”, “set” and “act” behaviors. That sort of integrates the “act” behavior with the 2nd setter, unifying bindings and actions. Of course, I haven’t worked it out in any detail, so the whole thing might be infeasible or just plain muddled.
Except that Swift has stored properties *and* computed properties, and computed properties have no implicit backing store. By definition, a computed setter can be *nothing but* side effects. As above, if there’s any backing store required, though, that drives you to a 2nd property, which is ugly and a little dangerous for the reasons stated. Again, we’re talking implementation here, not client API design. The difference between stored and computed properties is opaque to clients of the type, and I agree with you that the semantics *for the client* should be simple, kind of passive, and indistinguishable in the two cases. FWIW, this all came up for me in the context of wrapping UserDefaults in a customized Swift class that makes user defaults values available as apparently pure Swift properties. This gets hard because UserDefaults doesn’t have properties, it has key/values, which means the ultimate backing store is one of your “broader” cases, and the flow of KVO notifications is not under the wrapper’s direct control, *plus* there are updates arriving from internal sources (including other processes such as ‘defaults write …’ in Terminal!) as well as UI such as a preferences window. So far, I haven’t found a good solution that doesn’t involve the wrapper type having a 2nd private property (as a private backing store) for each property it makes public. |
|