Search code examples
swiftobjectpropertiesgetter-setter

Set dependent property variable with custom setter method for object in Swift


I have a class object property named object, and a boolean readonly variable named isEmpty. If the object property is set to some object, the isEmpty property is switched to false, and if the object is set as nil, isEmpty is set as true. I can achieve this using Objective-C as following:

@interface SomeObject: NSObject

@property (nonatomic, strong) id object;
@property (nonatomic, assign, readonly) BOOL isEmpty;

@end

@implementation SomeObject

- (void)object:(id)object {
    _isEmpty = NO;
    _object = object;
}

- (id)object {
    return _object;
}

- (void)clearObject {
    _object = nil;
    _isEmpty = YES;
}

@end

How can I imitate this in Swift 2.2? So far I have tried

class SomeObject: NSObject {
   public private(set) var isEmpty: Bool
   var nodeObject: AnyObject? = {
        get {
           isEmpty = false
           return object
        }
        set(_object: AnyObject) {
            object = _object
        }
    }
}

But it is not working, as expected! I know it is wrong, but not sure about which part!

TIA


Solution

  • Unless you have an absolute requirement to set isEmpty, I would go about it this way: create a getter for isEmpty and check whether nodeObject is null in the getter:

    class SomeObject {
      var isEmpty: Bool {
        get {
           return nodeObject == nil
        }
      }
      var nodeObject: AnyObject?
    }
    

    See fiddle: http://swiftlang.ng.bluemix.net/#/repl/57c73513458cfba6715ebebd

    EDIT: If you really want to get it close to Objective-C, I suggest this version:

    class SomeObject {
       private var _isEmpty: Bool = true
       var isEmpty: Bool {
           get {
               return _isEmpty
           }
       }
       var nodeObject: AnyObject? {
           didSet {
                _isEmpty = nodeObject == nil
           }
       }
    }
    

    Fiddle: https://swiftlang.ng.bluemix.net/#/repl/57c738b646a02c0452203f98