[swift-users] How to write better Swift
Gerriet M. Denkmann
g at mdenkmann.de
Mon Jul 10 11:02:41 CDT 2017
> On 10 Jul 2017, at 22:35, Geordie J via swift-users <swift-users at swift.org> wrote:
>
> Would “didSet" on a normal variable work for you?
willSet/didSet usually is a good solution (which I had forgotten about).
But in my case it seems not to help - see the corrected code below
> var status: Int {
> didSet { doSomething() }
> }
>
> Geordie
>
>
>> Am 10.07.2017 um 17:34 schrieb Gerriet M. Denkmann via swift-users <swift-users at swift.org>:
>>
>> 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}
oldDerived = derivedStatus // depends on status
privateStatus = new
newDerived = derivedStatus
if newDerived != oldDerived … do something …
… do something more here …
>> }
>> }
>> }
>>
>> But is this “privateStatus” really necessary?
>> If not, how can it be avoided?
Quincey had an excellent idea: one should be able to write:
var status: Int
{
var privateStatus: Int // makes it much clearer that privateStatus really only belongs to status
get{ return privateStatus }
set(new)
{
…
privateStatus = new
}
}
Gerriet.
More information about the swift-users
mailing list