Articles, podcasts and news about Swift development, by John Sundell.

Computed properties vs methods

Published on 06 Aug 2019

When picking between a computed property versus a method in Swift, I choose a property when:

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)
        }
    }
}

Support Swift by Sundell by checking out this sponsor:

Emerge

Emerge: Continuously monitor and reduce your app’s size. Emerge’s easy to use plugins for GitHub and fastlane will automatically scan your app’s binary and provide you with simple, actionable suggestions on how to make it smaller and, in turn, faster for your users to download. Set up a demo now!