Are computed properties evaluated each time they are accessed?

I have two questions about computed properties in Swift.

Are computed properties calculated every time they are accessed? Or are they stored somewhere for future access?

What property is this since I could not remove it:

let navigationController: UINavigationController = {
   var navigator = UINavigationController()
   navigator.navigationBar.translucent = false
   return navigator
}()

Is this checked every time every time you access it?

+4
source share
1 answer

This is NOT a computed property.

let navigationController: UINavigationController = {
   var navigator = UINavigationController()
   navigator.navigationBar.translucent = false
   return navigator
}()

This is just a stored property , populated with the result of the value returned by this block of code.

var navigator = UINavigationController()
navigator.navigationBar.translucent = false
return navigator

A block is executed when an instance of the class is created. Just one time.

So, I am writing this

struct Person {
    let name: String = {
        let name = "Bob"
        return name
    }() // <- look at these
}

struct Person {
    let name: String
    init() {
        self.name = "Bob"
    }
}

IMHO , :

  • "
  • clear
  • ,

# 1:

, (). , .

, () , - , . Swift stored closure. , UINavigationController.

.

struct Person {
    let sayHello: ()->() = { print("Hello") }
}

sayHello, . 0 Void.

let bob = Person()
bob.sayHello // this does NOT execute the code inside closure
bob.sayHello() // this does execute the code in the closure and does print the message

# 2:

, , a Computed Property. , , , a Computed Property , .

age. , , .

(age)

enter image description here

+10

Source: https://habr.com/ru/post/1626387/


All Articles