This article has been archived, as it was published several years ago, so some of its information might now be outdated. For more recent articles, please visit the main article feed.
Computed properties vs methods
When picking between a computed property versus a method in Swift, I choose a property when:
- The API I’m defining returns some form of information about an object or value’s state.
- Its body can be executed in
O(1)
time.
extension TodoItem {
// Returning information about an object/value's state in
// constant time = property.
var isCompleted: Bool {
return state == .completed
}
// Returning a new value after applying a mutation = method.
func completed() -> TodoItem {
var item = self
item.state = .completed
return item
}
// Returning information, but in a way that's slower than
// constant time (O(n), where N is the number of attachments
// in this case) = method.
func attachmentTags() -> Set<Tag> {
return attachments.reduce([]) { tags, attachment in
tags.union(attachment.tags)
}
}
}

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.