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 price from different values outlined on the identical object. Having the ability to do that is tremendous handy as a result of it implies that we don’t need to manually guarantee 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 price:

struct Person {
  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 can we make a selection between a perform with no arguments and a computed property?

I prefer to preserve the next guidelines of thumb in thoughts:

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

In fact, these are all simply my opinions however I’ve discovered that almost all builders that I’ve labored with through the years both agree with these guidelines or have guidelines which might be solely barely totally different from mine.

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



Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox