Swift

Swift

Made by DeepSource

@IBOutlets shouldn’t be declared as weak SW-W1020

Bug risk
Major
Autofix

By declaring @IBOutlets as weak, you are creating a weak reference to the outlet. Weak references do not keep the referenced object alive, meaning that the outlet can be deallocated if there are no other strong references to it. This can result in unexpected crashes or undefined behavior when accessing the outlet.

By setting outlets to be strong in view controllers, you can ensure that all your UI elements will be in memory when you call upon them. If they were weak, you could experience a nil pointer exception when trying to change label text or capture user interaction with a button.

Apple officially recommends that IBOutlets should be strong. The only case when an IBOutlet should be weak is to avoid a retain cycle, which might arise when custom views have references to views upstream in the view hierarchy, however, having such a design is not a recommended practice.

Bad Practice

class ViewController: UIViewController {
  @IBOutlet weak var label: UILabel?
}

Recommended

class ViewController: UIViewController {
  @IBOutlet var label: UILabel?
}