Learn Courses My Dashboard

Why should i use Computed properties?

For example:
var a = “hi”
var b = “456”
var d = a + b

d has the same result as below E:

var E:String {
return a + b
}

then how can I know when should I use it directly or Computed properties?

thanks, in advance!

Because you can’t do something like this:

struct Item {
    var a = "hi"
    var b = "456"
    var d = a + b
}

This will give you compiler errors:

Cannot use instance member ‘a’ within property initializer; property initializers run before ‘self’ is available
Cannot use instance member ‘b’ within property initializer; property initializers run before ‘self’ is available

But you can do this:

struct Item {
    var a = "hi"
    var b = "456"
    var d: String { a + b } 
}

Also, even if you could do the former, it would set d to the value of a + b when you first initialized the struct, but wouldn’t keep it equal to a + b if you ever changed either of those properties. Using a computed property for d will keep them in sync.

And those are just two reasons why you should use computed properties. I suggest reading the Computed Properties section of the Language Guide for more information.

1 Like

Thanks. roosterboy