Programming in Swift: Functions & Types

Jan 4 2022 · Swift 5.5, iOS 15, Xcode 13

Part 4: Properties & Methods

35. Computed Properties or Methods?

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 34. Challenge: Methods Next episode: 36. Conclusion

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 35. Computed Properties or Methods?

Update Notes: This course was originally recorded in 2019. It has been reviewed and all content and materials updated as of October 2021.

Transcript: 35. Computed Properties or Methods?

At this point, you’ve learned about two ways you can run code inside structures: computed properties and methods.

You may wonder: in which situations should you use one or the other? Well, most of the time, this will probably end up being clear enough. With a property, you’ll need to be able to get a value, using no arguments. And sometimes, you should be able to set a property’s value as well.

If what you need doesn’t match up with the concept of getting (and maybe setting) a single value, then a method is the way to go. But you can have a method that takes no arguments, and returns a single value. Should you use that, or a get-only computed property, instead?

In the end, the choice comes down to a matter of style, but a lot of your fellow developers are going to associate properties with the idea that they’re cheap to compute. (At least after the first time, if we’re talking about lazy variables.) If the computation you’re doing is not extremely fast, then consider using a method.

And maybe, use a different naming convention, for get-only properties, and methods that get values. For example, the Wizard type we worked with in the video on properties had a “fullName” property. If I were going to use a method instead, I’d call it “getFullName”.

Read a lot of other people’s code, and write a lot of your own. Experiment with a ton of methods and properties in your apps, and you’ll develop your own guidelines on what you think makes sense.