Tuesday, May 7, 2024
HomeIOS DevelopmentDeciding between a computed property and a perform in Swift – Donny...

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 signifies that we don’t should manually ensure 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 can we make a selection between a perform with no arguments and a computed property?

I prefer to hold 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, you must 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 needs to be “easy”. That is in all probability probably the most subjective of all however in case 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 needs 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 matches the non deterministic habits higher for my part.

After all, these are all simply my opinions however I’ve discovered that the majority 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!



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments