Swift supports lazy
variable in struct
/ class
definition as follows:
struct SomeStruct {
lazy var x: Int = 0
}
But currently Swift doesn't support to define functions with lazy
parameters. I propose the following language feature:
func f(x: lazy Int) {
// do something
}
which is equivalent to the following to some extent:
func f(x: () -> Int) {
// do something
}
With the lazy
keyword, the expression which is passed to the lazy parameter won't be evaluated until being used in the function body:
f(1+2)
For example, here 1+2
won't be evaluated until x
is being used in the function f
.
Use case:
- overload
|
or||
to support short-circuit evaluation:
struct S {}
func | (lhs: S, rhs: lazy S) -> S {
// do something
}
So if lhs
meet some condition, rhs
won't be evaluated.