在swift中是否可以从属性的声明中分离set,get,willSet和willGet?

时间:2014-07-26 12:58:59

标签: properties swift

我将首先向您展示我正在开展的项目中的一些属性......

/**  Properties  **/
var coordinates: Coordinates

var text: NSString = "" {
didSet {
    self.needsDisplay = true
}
}

var boxViewGroup: GridBoxViewGroup

var isLocked: Bool = false {
willSet {
    if isSelected || !newValue {
        boxViewGroup.selectedBox = nil
    }
}
}
var isSelected: Bool {
get {
    if boxViewGroup.selectedBox {
        return boxViewGroup.selectedBox === self
    }
    else {return false}
}
}

var invertedFrame: NSRect {
get {
    return NSRect(x: frame.origin.x,
                  y: superview.bounds.height - frame.origin.y,
              width: bounds.size.width,
             height: bounds.size.height)
}

set {

    self.frame = NSRect(x: newValue.origin.x,
                        y: superview.bounds.height - newValue.origin.y - newValue.height,
                    width: newValue.width,
                   height: newValue.height)
}
}

这看起来有点乱。所以我的问题是可以将get,set,willGet和willSet方法放在一个单独的位置,以便我的属性声明看起来像这样......

var coordinates: Coordinates
var boxViewGroup: GridBoxViewGroup
var isSelected: Bool
var invertedFrame: NSRect

看到这样我实际上可以告诉它们有哪些属性。

1 个答案:

答案 0 :(得分:1)

通过吐入2个课程是可能的。您可以覆盖子类中的属性声明并添加Property Observers

class DataA {
  var coordinates: Coordinates
  var boxViewGroup: GridBoxViewGroup
  var isSelected: Bool
  var invertedFrame: NSRect
}

class A : DataA {
  override var coordinates: Coordinates {
  didSet {
    //add code
  }
  willSet(newValue) {
    //add code 
  }
  } 
}

在Apple文档中了解有关Property Overriding的更多信息