为什么 SnapKit 的 makeConstraints 函数的闭包中没有 self?
Why there is no `self` in the closure in the function `makeConstraints` by SnapKit?
starLabel.snp.makeConstraints { make in
make.left.equalTo(starImageView.snp.right).offset(5)
make.centerY.equalToSuperview()
}
starImageView
和 starLabel
是当前视图控制器的属性。但是,为什么我可以忽略闭包中的 self
(self.starImageView
),它是 makeConstraints
中的参数?
并且在我的闭包中,我必须显式地写self
,否则编译器会报错:
Reference to property 'starImageView' in closure requires explicit 'self.' to make capture semantics explicit
Insert 'self.'
因为equalTo
是这样的:
public func equalTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .equal, file: file, line: line)
}
而 ConstraintRelatableTarget
是一个协议,它导致不同的类型,如 Int、Float 等。您还引用了 ConstraintItem
,在这种情况下,您引用的是视图,这是这样的:
internal weak var target: AnyObject?
internal let attributes: ConstraintAttributes
internal init(target: AnyObject?, attributes: ConstraintAttributes) {
self.target = target
self.attributes = attributes
}
internal var layoutConstraintItem: LayoutConstraintItem? {
return self.target as? LayoutConstraintItem
}
看起来,Any?
和 AnyObject?
(我不认为它必须是可选的)都不需要达到 self。因此,您输入 equalTo
函数的任何内容都会被 snapKit
视为 AnyObject?
,因此不需要 self
引用。
public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
ConstraintMaker.makeConstraints(item: self.view, closure: closure)
}
因为闭包不是@escaping
,所以这意味着闭包只会在函数中运行。当函数结束时关闭就会被释放。
只有函数才能持有闭包。
starLabel.snp.makeConstraints { make in
make.left.equalTo(starImageView.snp.right).offset(5)
make.centerY.equalToSuperview()
}
starImageView
和 starLabel
是当前视图控制器的属性。但是,为什么我可以忽略闭包中的 self
(self.starImageView
),它是 makeConstraints
中的参数?
并且在我的闭包中,我必须显式地写self
,否则编译器会报错:
Reference to property 'starImageView' in closure requires explicit 'self.' to make capture semantics explicit
Insert 'self.'
因为equalTo
是这样的:
public func equalTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .equal, file: file, line: line)
}
而 ConstraintRelatableTarget
是一个协议,它导致不同的类型,如 Int、Float 等。您还引用了 ConstraintItem
,在这种情况下,您引用的是视图,这是这样的:
internal weak var target: AnyObject?
internal let attributes: ConstraintAttributes
internal init(target: AnyObject?, attributes: ConstraintAttributes) {
self.target = target
self.attributes = attributes
}
internal var layoutConstraintItem: LayoutConstraintItem? {
return self.target as? LayoutConstraintItem
}
看起来,Any?
和 AnyObject?
(我不认为它必须是可选的)都不需要达到 self。因此,您输入 equalTo
函数的任何内容都会被 snapKit
视为 AnyObject?
,因此不需要 self
引用。
public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
ConstraintMaker.makeConstraints(item: self.view, closure: closure)
}
因为闭包不是@escaping
,所以这意味着闭包只会在函数中运行。当函数结束时关闭就会被释放。
只有函数才能持有闭包。