Thursday, June 13, 2024
HomeIOS DevelopmentDeciding between a computed property and a operate in Swift

Deciding between a computed property and a operate in Swift


Printed on: April 26, 2024

In Swift, we will use computed properties to derive a price 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 must manually make it possible for we replace derived properties each time one of many “supply” values modified. We’ll simply recompute the property each time it’s accessed!

Should you choose to be taught from video, here is the companion video for this weblog publish:

That is similar to having a operate 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 will we make a selection between a operate 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 uncomfortable side effects; if accessing the property mutates any values in your object, it is best to use a operate.
  • Accessing a property ought to (ideally) have O(1) complexity (be taught extra about Massive-O and what O(1) means proper right here. For capabilities it is extra anticipated that they is perhaps O(n) or worse.
  • Your property’s computation needs to be “easy”. That is in all probability probably the most subjective of all however when you’re writing greater than a handful of traces it is best to ask your self whether or not a operate would look higher.
  • The property’s output needs to be deterministic. In different phrases, accessing the identical property a number of occasions in a row ought to get me the identical end result each time. If not, use a operate; it suits the non deterministic conduct higher for my part.

After I apply these guidelines to the instance above, I might decide a computed property for this one. We will compute the identify in fixed time, the property’s getter can be easy (one line), and the output is totally freed from any side-effects. An ideal candidate for a computed property.

In fact, 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 totally different from mine.

How do you determine between a operate 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