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.
1 Like
Jumhyn
(Frederick Kellison-Linn)
2
This is basically what we have @autoclosure for. It is slightly more syntax heavy on the callee side, since you’re required to call a function farther than just use the value, but it fills basically this exact purpose (and is used already in the Bool operators for short circuiting):
public static func && (lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows
-> Bool {
return lhs ? try rhs() : false
}
20 Likes