Shabib
Shabib

Reputation: 1697

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

Upvotes: 0

Views: 326

Answers (3)

MK_Dev
MK_Dev

Reputation: 3333

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

Upvotes: 1

Dustin Spengler
Dustin Spengler

Reputation: 7691

would this work for you?:

class SomeObject: NSObject {
    var isEmpty: Bool
    var nodeObject: AnyObject? {
        didSet {
            if nodeObject != nil {
                isEmpty = false
            } else {
                isEmpty = true
            }
        }
    }
}

Upvotes: 1

Mr. Xcoder
Mr. Xcoder

Reputation: 4795

Try this for the SWIFT 2 version:

class SomeObject: NSObject {
    var object: AnyObject? {
        return object
    }
    private(set) var isEmpty = false


    func object(object: AnyObject) {
        self.isEmpty = false
        self.object = object!
    }

    func clearObject() {
        self.object = nil
        self.isEmpty = true
    }
}

Upvotes: 0

Related Questions