iOS CallAsFunction() in Swift 5.2
Overview:
- Swift introduces statically callable values.
- It's a fancy way of saying that you can now call a value directly.
- 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
Here you can just call the object of struct like a function and you will get a (age) value from the function.
Here:
- You can add
mutating
before the function. - You can return the value of the function.
- 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
Add below line into button action
Reference:
Let's grow together 🌱
Cheers 🍻