0

What is the diferences?


let tableView: UITableView = {
   let tabView = UITableView()
    
    return tabView
}()

var tableView2: UITableView {
    let tabView = UITableView()
    return tabView
}

Where to find more about this subject?

  • Add `print("tableView")` & `print("tableView2")` before the corresponding getter, and do `_ = myObjectWichHasTheseProperties.tableView` twice, and `_ = myObjectWichHasTheseProperties.tableView2` twice too. What's the output in console? – Larme Apr 19 '23 at 15:03
  • You can also print the value of each returned vale with https://stackoverflow.com/questions/24058906/printing-a-variable-memory-address-in-swift and see that `tableView2` is never the same one. – Larme Apr 19 '23 at 15:08
  • 1
    This is the same as yours; you just need to learn that `get` can be implicit: [Difference between computed property and property set with closure](https://stackoverflow.com/questions/31515805/difference-between-computed-property-and-property-set-with-closure) –  Apr 19 '23 at 15:51

1 Answers1

0

The first code snippet defines a constant tableView which is a closure that creates a new UITableView object and returns it. This is known as a "lazy initialization" technique, where the table view is only created when it is needed, and not when the constant is declared.

The second code snippet defines a computed property tableView2 which is a function that creates a new UITableView object and returns it. This means that every time tableView2 is accessed, a new UITableView object will be created.

The key difference between the two is that tableView is a constant closure that creates a UITableView object lazily, while tableView2 is a computed property that creates a new UITableView object every time it is accessed.

In general, the lazy initialization approach (like the first code snippet) is more memory-efficient since the object is only created when it is needed. However, the computed property approach (like the second code snippet) can be more flexible since it allows for more complex logic in creating the object.

Kudos
  • 1,224
  • 9
  • 21