Skip to content

iOS CallAsFunction() in Swift 5.2

Platform Language License

Overview:

  1. Swift introduces statically callable values.
  2. It's a fancy way of saying that you can now call a value directly.
  3. You can use callAsFunction

For Example: Create a Age struct that has property of birthYear, then add callAsFunction(). So everytime you call a Age you will get your age.

Above Swift 5.2:

struct Age {
    var birthYear: Int

    func callAsFunction() -> Int {
        //get the current year
        let year = Calendar.current.component(.year, from: Date())
        return (year - birthYear)
    }
}

Now you can just call like below line

let ageObjc = Age(birthYear: 1991)
print(ageObjc())

Here you can just call the object of struct like a function and you will get a (age) value from the function.

ageObjc()

Here:

  1. You can add mutating before the function.
  2. You can return the value of the function.
  3. You can add as many parameters as you want.

Example:

Another example: We can create Dice struct that has properties for lowerValue and upperBound

struct Dice {
    var min: Int
    var max: Int

    func callAsFunction() -> Int {
        (min...max).randomElement()!
    }
}

Declare this globally

let dice = Dice(min: 1, max: 6)

Add below line into button action

let rolls = dice()
print(rolls)

Reference:

Github Github

Let's grow together 🌱

Cheers 🍻