Question about the use of self on page 146


#1

Could a more experienced coder please try to explain to me why self is used this way in this code?

I can’t seem to add indentation in this comment box, so I took a screen shot as well.

func animateLabelTransitions() {
let animationClosure = { () -> Void in
self.questionLabel.alpha = 1
}
// Animate the alpha
UIView.animate(withDuration: 0.5, animations: animationClosure)
}

self%20screens

I understand that the “self property is used to refer to the current instance within its own instance methods”, but I think I’m missing how that applies here.

I also don’t understand why UIView.animate is used instead of UILabel.animate. UILabel inherits from UIView, so?

Thanks for your help!


#2

I could be wrong here, but I think you must always explicitly declare ‘self’ within a closure.


#3

Theoretically speaking, it is not needed. But Xcode insists on it only because to force the programmer to explicitly declare that an object instance is being captured by ARC, which is for a good cause.

typealias Jabber = (Int) -> Int

func jibber (jabber:Jabber) {
    print (jabber (17))
}

class Foo {
    var boo = 9
    
    func fib () {
        let fob = {(s:Int) -> Int in boo = 7 * s
            // Xcode says: Reference to property 'boo' in closure requires explicit 'self.' to make capture semantics explicit
            return boo
            // Xcode says: Reference to property 'boo' in closure requires explicit 'self.' to make capture semantics explicit

        }
        jibber (jabber:fob)
    }
}