3
starLabel.snp.makeConstraints { make in
    make.left.equalTo(starImageView.snp.right).offset(5)
    make.centerY.equalToSuperview()
}

The starImageView and starLabel are the properties of current view controller. But, why can I ignore the self(self.starImageView) in the closure which is the param in makeConstraints?

And in my closure, I must write the self explicitly, or the compiler will report a error:

Reference to property 'starImageView' in closure requires explicit 'self.' to make capture semantics explicit

Insert 'self.'

enter image description here

Community
  • 1
  • 1
Desgard_Duan
  • 659
  • 1
  • 6
  • 12

2 Answers2

2
public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
        ConstraintMaker.makeConstraints(item: self.view, closure: closure)
}

Because the closure is not @escaping,so it means the closure will just run in the function. When the function over the closure will be released. Only the function can hold the closure.

Yan
  • 287
  • 3
  • 11
-1

It's because equalTo looks like this:

public func equalTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
    return self.relatedTo(other, relation: .equal, file: file, line: line)
}

And ConstraintRelatableTarget is a protocol that leads to different types as Int, Float etc. You also have a reference to a ConstraintItem which is this case is the view you refer to, and this is how it looks:

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
}

As it appears, both Any? and AnyObject? (I dont think it has to be optional) does not need self to be reached. Hence, anything you put in to the equalTo function, is seen by snapKit as an AnyObject? and therefor don't need a self reference.

Vollan
  • 1,887
  • 11
  • 26