Last Updated: April 20, 2021
·
675
· luigledr

Don't waste your creativity for redefine self names inside closures in Swift.

Some times is hard to define good names for variables while we are coding, and in Swift with their great resources, it is especially true.

When writing closures inside classes, it's a good practice to keep atention when you need to access self. If you don't take care and use [weak self] or [unowned self], you could create a circular reference to your class and keeping it in memory, even when you don't need it anymore.

When we use [weak self] in a closure we need to look at self to guarantee it isn't null. If we don't do it, we could brake our application.

To keep guarantee that self is pointing to an valid instance we can use guard like this: guard let _self = self else.... When we use guard statement in this situation, we need to redefine self's name, and we know how hard is to create great variable names.

Recently I discovered a Swift sugar code that allow-me to use reserved language words as names of variables. This is not exactly a good practice, but I thought if it was possible to use this sugar code to keeping using self name for weak references inside my closures!

To do it, we just need to use grave accent to embrace our self name redefinition in guard statement. Example:

class test {
    let asyncValidator = validator()
    var model: people
    func save() {
        // Do Save logic
    }

    func validate() {
        asyncValidator.validate(entity: people) { [weak self] (result: Bool) in 
            guard let `self` = self else { return }

            if result {
               self.save()
            }
        }
    }
}

3 Responses
Add your response

:) nicely dont get it -- why would you need `` around string here?! It compiles just fine without it .. given I fix value == "" to string==""

over 1 year ago ·

to show `use e.g.if` - so you really use a keyword. it isnt a good Idea though

over 1 year ago ·

I re-writed the example using self in a context of a clousure, as I said, isn't a good idea to use reserved words as variable names, but self is a variable name, so I think the example fits better. :) Tks for your observations @daij-djan.

over 1 year ago ·