Deciding between a computed property and a function in Swift

Published on: April 26, 2024

In Swift, we can use computed properties to derive a value from other values defined on the same object. Being able to do this is super convenient because it means that we don’t have to manually make sure that we update derived properties every time one of the “source” values changed. We’ll just recompute the property every time it’s accessed!

If you prefer to learn from video, here's the companion video for this blog post:

This is very similar to having a function that takes no arguments and returns a value:

struct User {
  let givenName: String
  let familyName: String

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

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

So how do we make a choice between a function with no arguments and a computed property?

I like to keep the following rules of thumb in mind:

  • Accessing a property should never have side effects; if accessing the property mutates any values on your object, you should use a function.
  • Accessing a property should (ideally) have O(1) complexity (learn more about Big-O and what O(1) means right here. For functions it's more expected that they might be O(n) or worse.
  • Your property’s computation should be “simple”. This is probably the most subjective of all but if you’re writing more than a handful of lines you should ask yourself whether a function would look better.
  • The property’s output should be deterministic. In other words, accessing the same property multiple times in a row should get me the same result every time. If not, use a function; it fits the non deterministic behavior better in my opinion.

When I apply these rules to the example above, I would pick a computed property for this one. We can compute the name in constant time, the property's getter would be simple (one line), and the output is completely free of any side-effects. A perfect candidate for a computed property.

Of course, these are all just my opinions but I’ve found that most developers that I’ve worked with over the years either agree with these rules or have rules that are only slightly different from mine.

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

Subscribe to my newsletter