-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Mastering Swift 5.3
By :

With SE-0253 in Swift 5.2, we are able to call a type as a function. To explain it a little better, instances of types that have a method whose name is callAsFunction
can be called as if they were a function. Let's look at an example of this. We will start off by creating a Dice
type that can be used to create an instance of any size dice:
struct Dice {
var highValue: Int
var lowValue: Int
func callAsFunction() -> Int {
Int.random(in: lowValue...highValue)
}
}
Notice the method within the function called callAsFunction(). This function generates a random number using the lowValue
and highValue
properties. Since we named this method callAsFunction
, we are able to call it using the instance's name as if it were a function. Let's see how this works by creating a six-sided dice and generating a random value:
let d6 = Dice(highValue: 6, lowValue: 1)
let roll = d6()
The roll
variable will contain...