> On Apr 17, 2017, at 3:24 AM, Rick Mann <rm...@latencyzero.com> wrote:
> 
> I have a number of properties in Objective-C written like this, 
> short-circuiting notifications when the value doesn't change:
> 
> -------------
> @synthesize version = mVersion
> 
> - (void)
> setVersion: (NSString *) inVersion
> {
>    if (inVersion == nil && mVersion == nil)
>    {
>        return;
>    }
>    if ([inVersion isEqualToString: mVersion])
>    {
>        return;
>    }
> 
>    [self willChangeValueForKey: @"version"];
>    mVersion = inVersion;
>    [self didChangeValueForKey: @"version"];
> }
> -------------
> 
> Now I want to translate this method into Swift. Thing is, AFAIK you can't 
> name the ivar created for a property. Is there a way to translate this to 
> swift?

I’ve been converting a lot of KVO properties to Swift lately. Here’s how I’d do 
this:

// Only needed if the property will be accessed by Objective-C code, since 
Swift code won’t see the swizzled accessors anyway for a non-dynamic property.
// @objc annotation is needed on every method we write here, since otherwise 
it’ll quit working when @objc inference is removed in Swift 4 (SE-0160)
@objc private static let automaticallyNotifiesObserversOfVersion: Bool = false

// Our actual version property. If you want, you can create a private property 
named “mVersion” and it will function like an instance variable.
// But I’d probably just use willSet and didSet.
// Note that this doesn’t need to be dynamic, since we are not relying on 
Cocoa’s built-in automatic swizzling,
// which is only needed if we are not calling willChangeValue(forKey:) and 
didChangeValue(forKey:) ourselves.
@objc var version: String {
    willSet {
        // Send the willChange notification, if the value is different from its 
old value.
        if newValue != self.version {
            self.willChangeValue(forKey: #keyPath(version))
        }
    }
    didSet {
        // Send the didChange notification, if the value is different from its 
old value.
        if oldValue != self.version {
            self.didChangeValue(forKey: #keyPath(version))
        }
    }
}

Charles

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to