Search code examples
iosswiftclosuressnapkit

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

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


Solution

  • 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.