Functions in Swift – Swift Functions vs Computed Properties

functionsswift-language

Say I have have a class Event as follows:

class Event {
    private var attendees: [Person] = []

    // Case 1
    //*******
    // Should I use a func…
    func countOfAttendees() -> Int {
        return attendees.count
    }

    // …or a var
    var countOfAttendees: Int {
        return attendees.count
    }

    // Case 2
    //*******
    // Should I use a func…
    func countOfPaidAttendees() -> Int {
        return attendees.filter({$0.hasPaid}).count
    }

    // …or a var
    var countOfPaidAttendees: Int {
        return attendees.filter({$0.hasPaid}).count
    }
}

Is it best practice to use functions or computed properties in the 2 cases indicated above?

Best Answer

Follow the Uniform Access Principle,

All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation

To me, this means that I don't write funcs that take no arguments and return a value. I always use computed properties. That way, if I later decide to change the computed property into a stored property, I can do so without having the urge to remove the parens everywhere in my app and without having a separate "getter" method that just returns the value of a stored property, which seems pretty wasteful IMHO.

And if I change a stored property into a computed one, I don't have to add parens to the end of it, and everywhere that it is used in the app.

Related Topic