Call instances as a functions

Today we are going to talk about a small addition to the Swift language which introduces the ability to call instances of classes and structs as functions.

All we need to do is introduce a method called callAsFunction in our class or struct. Let’s see an example:

Let’s say that we need to implement some cache validation. Normally, I implement this kind of behavior inside a class or struct with a static method.

struct StaticCacheValidator {
    
    static func isValid() -> Bool {
        //Some logic validation
        return true
    }
}

let isValid = StaticCacheValidator.isValid()

The same logic with callAsFunction looks like this:

struct CacheValidator {
    
    func isValid() -> Bool {
        //Some logic validation
        return true
    }
    
    func callAsFunction() -> Bool {
        return isValid()
    }
}

let validator = CacheValidator()
let isValid = validator()

We create an instance and call the instance as if it were a method

We can even have multiple overloads of callAsFunction:

struct PolicyValidator {
    
    func callAsFunction() -> Bool {
        return true
    }
    
    func callAsFunction() -> String {
        return "Some string"
    }
    
    func callAsFunction(parameter: Int) -> String {
        return "Some \(parameter)"
    }
}

let validator = PolicyValidator()
let boolValue: Bool = validator()
let stringValue: String = validator()
let string2 = validator(parameter: 3)

Is it useful? Well, in my opinion, unless the class or struct needs to hold some state, I prefer to hold this kind of logic as a static method. However, it’s a good resource to know which can be handy when a class needs to hold some state and its main responsibility is to implement a single method.