8.4 C
London
Saturday, April 27, 2024

Deciding between a computed property and a perform in Swift – Donny Wals


Printed on: April 26, 2024

In Swift, we are able to use computed properties to derive a worth from different values outlined on the identical object. With the ability to do that is tremendous handy as a result of it implies that we don’t should manually be sure that we replace derived properties each time one of many “supply” values modified. We’ll simply recompute the property each time it’s accessed!

That is similar to having a perform that takes no arguments and returns a worth:

struct Consumer {
  let givenName: String
  let familyName: String

  // Ought to we use this?
  var fullName: String {
    return "(givenName) (familyName)"
  }

  // Or this?
  func fullName() -> String {
    return "(givenName) (familyName)"
  }
}

So how will we make a alternative between a perform with no arguments and a computed property?

I wish to maintain the next guidelines of thumb in thoughts:

  • Accessing a property ought to by no means have unwanted side effects; if accessing the property mutates any values in your object, you must use a perform.
  • Accessing a property ought to (ideally) have O(1) complexity (be taught extra about Huge-O and what O(1) means proper right here.
  • Your property’s computation ought to be “easy”. That is most likely probably the most subjective of all however when you’re writing greater than a handful of traces you must ask your self whether or not a perform would look higher.
  • The property’s output ought to be deterministic. In different phrases, accessing the identical property a number of instances in a row ought to get me the identical outcome each time. If not, use a perform; it suits the non deterministic habits higher for my part.

After all, these are all simply my opinions however I’ve discovered that almost all builders that I’ve labored with over time both agree with these guidelines or have guidelines which might be solely barely completely different from mine.

How do you determine between a perform or a computed var? Let me know on Mastodon or Twitter!



Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here