协议的属性声明中“获取”是什么意思?

时间:2017-05-19 00:12:25

标签: swift properties protocols

我正在查看自动布局库中的一些代码。其中,UIView采用了一种协议:

extension UIView: Constrainable {}
extension UILayoutGuide: Constrainable {
    // LayoutGuide doesn't have baseline anchors, so just use the bottom anchor
    public var firstBaselineAnchor: NSLayoutYAxisAnchor {
        return bottomAnchor
    }
    public var lastBaselineAnchor: NSLayoutYAxisAnchor {
        return bottomAnchor
    }
}

public protocol Constrainable {
    var topAnchor:      NSLayoutYAxisAnchor { get }
    var bottomAnchor:   NSLayoutYAxisAnchor { get }
    var leftAnchor:     NSLayoutXAxisAnchor { get }
    var rightAnchor:    NSLayoutXAxisAnchor { get }
    var leadingAnchor:  NSLayoutXAxisAnchor { get }
    var trailingAnchor: NSLayoutXAxisAnchor { get }

    var centerXAnchor:  NSLayoutXAxisAnchor { get }
    var centerYAnchor:  NSLayoutYAxisAnchor { get }

    var widthAnchor:    NSLayoutDimension { get }
    var heightAnchor:   NSLayoutDimension { get }

    var firstBaselineAnchor : NSLayoutYAxisAnchor { get }
    var lastBaselineAnchor  : NSLayoutYAxisAnchor { get }
}

{ get }完成了什么?

1 个答案:

答案 0 :(得分:3)

这些是采用协议的类必须提供getter的属性。该协议没有指定有关setter的任何内容,因此类可以提供计算属性而不是存储的属性。

例如,采用printf的班级可以通过添加

来满足Constrainable的要求
topAnchor

或添加

var topAnchor: NSLayoutYAxisAnchor