在Swift中为对象设置依赖属性变量和自定义setter方法

时间:2016-08-31 19:31:47

标签: swift object properties getter-setter

我有一个名为object的类对象属性,一个名为isEmpty 的布尔只读变量。如果object属性设置为某个对象,则isEmpty属性将切换为false,如果该对象设置为nil,则isEmpty将设置为true。我可以使用Objective-C实现此目的:

@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

我如何在Swift 2.2中模仿这个?到目前为止我已经尝试了

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

但它没有按预期工作!我知道这是错的,但不确定哪个部分!

TIA

3 个答案:

答案 0 :(得分:1)

这对你有用吗?:

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

答案 1 :(得分:1)

除非你有绝对的要求设置isEmpty,否则我会这样做:为isEmpty创建一个getter并检查getter中的nodeObject是否为null:

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

请参阅小提琴:http://swiftlang.ng.bluemix.net/#/repl/57c73513458cfba6715ebebd

编辑:如果你真的想让它接近Objective-C,我建议这个版本:

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

小提琴:https://swiftlang.ng.bluemix.net/#/repl/57c738b646a02c0452203f98

答案 2 :(得分:0)

尝试使用 SWIFT 2 版本:

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
    }
}