Swift 4.2 Brief analysis using self as variable name

  • 2020-06-15 10:21:51
  • OfStack

preface

Swift 4.2 is the second minor update to Swift 4, bringing with it many great improvements - making this a big year for Swift and confirming that this community-driven evolution of Swift is making a great language better.

In the Swift 4.2 update, there are four main elements:

Faster compilation New language features improve efficiency and remove boilerplate code SDK improvements to Swift Improved 2 base compatibility

Prior to 4.2, self was the global reserved keyword, so if in the escape closure if self was marked as weak in the closure, the 'would be used if:


guard let `self` = self else { return }

While this solves the variable name problem, it also creates another problem: there is no variable named self displayed in the console. So there is also a common practice of using individual names, such as strongSelf:


doSomething(then: { [weak self] in
 guard let strongSelf = self { else return }
 strongSelf.doSomethingElse()
)

This approach does the trick, but a novice developer would be baffled.

All I can do, of course, is give Dad Apple a lot of advice. In 4.2, Apple finally responded! self is no longer a reserved keyword in otional binding.

Now it's fair to write:


guard let self = self else { return }

Of course, removing this limit also means that self may not always be self:


  var number: Int? = nil
  if let self = number {
  print(self) //  Here,  self  is  number : Int
  }

Hopefully, when you use self as the name of the optional binding variable, you still use it in the right place to avoid other complications.

conclusion


Related articles: