Swift function vs lazy var vs computed property - difference?

  • lazy vars are actually stored properties, so you can't put it in extensions or anywhere stored properties are not allowed.
  • The getter for computed properties is run every time you refer to that property. This can be significant especially if the getter is time-consuming or has side-effects to other parts of the code.
  • The getter for lazy vars are only run when the property is first referred to and never again.
  • lazy vars are variables. You can mutate them.
  • Computed properties can optionally have a setter, so sometimes they are read-only.
  • Using a function like that is very similar to a read only computed property. You just have to add () when getting its value.

The first one:

lazy var profileImageIsLoaded: Bool = {
    return (profileImageView.image != nil) && (profileImageProgressView.alpha == 0.0)
}()

profileImageIsLoaded is a stored property that is initialized lazily using a closure, once the variable has been initialized this closure will not be called anymore and the value it took the first time the closure was called will be returned.

The second one:

func profileImageIsLoaded() -> Bool {
    return (profileImageView.image != nil) && (profileImageProgressView.alpha == 0.0)
}

Is a normal function declaration, this is declaration only. If you wanted to call that function you'll do that like this: profileImageIsLoaded().

The third one:

var profileImageIsLoaded: Bool {
    return (profileImageView.image != nil) && (profileImageProgressView.alpha == 0.0)
}

profileImageIsLoaded is a computed property, each time you access this property, it will be computed and returned.

Choosing which one to use always depends on your situation.

Tags:

Swift