Cristik
Cristik

Reputation: 32785

Property getter as function

Is it possible to access the getter of a property, so that it can be passed along to functions like filter/map/reduce?

For example, assuming I have a User entity:

struct User {
    let firstName: String
    let lastName: String
    let isUnderaged: Bool

    func fullName() -> String {
        return "\(firstName) \(lastName)"
    }
}

let users: [User] = [] // or some computed result

If I need to filter all users that are underaged, then I need to create a temporary, anonymous, closure that only returns the isUnderaged value:

let underagedUsers = users.filter { $0.isUnderaged }

Similar, if I want to collect all the given names:

let givenNames = users.map { $0.firstName }

, I have to create another anonymous closure.

The fullName() method, on the other hand can be nicely passed along:

let allNames = users.map(User.fullName)

#selector accepts the #selector(getter: User.isUnderaged) form (User would need to be a class for this to work, just used it as example).

Does Swift supports something like this - passing getters to functions that allow closures?

Searching for something similar to this users.filter(User.isUnderaged) - this currently doesn't compile as isUnderaged cannot be accessed without an instance.

Upvotes: 2

Views: 575

Answers (1)

Cristik
Cristik

Reputation: 32785

Starting with Swift 5.2, this is now possible, thanks to this Swift Evolution proposal.

Basically, key paths can now be used in places where functions are needed, like map/filter, etc.

For the example from the question, the usage would be along the lines of:

users.filter(\.isUnderaged)
users.map(\.firstName.count) // yes, chaining is also permitted

Upvotes: 1

Related Questions