Evaluating lazy functions in swift
I wonder if a simple if statement can be lazily evaluated. Below is an example that will print "this foo" and "this bar", but I really want it to only print the first line:
func foo() {
println("this is foo")
}
func bar() {
println("this is bar")
}
func maybeFooOrBar(isFoo: Bool) {
let myFoo = foo()
let myBar = bar()
isFoo ? myFoo : myBar
}
source to share
Don't know if you want this, you can use the function as type
func foo() {
println("this is foo")
}
func bar() {
println("this is bar")
}
func maybeFooOrBar(isFoo: Bool) {
let myFoo = foo
let myBar = bar
let result = isFoo ? myFoo : myBar
result()
}
Then if you callmaybeFooOrBar(true)
print the first function callmaybeFooOrBar(false)
wii prints the second function
Alternatively, it can be done in a clear way
func maybeFooOrBar(isFoo: Bool) {
(isFoo ? foo : bar)()
}
source to share
I can't find canonical proof that Swift is not a lazy evaluative language , but I'm sure the community will correct me if I'm wrong!
Since it is not lazy, method calls are simply executed in order, rather than determining which methods should not be called.
To achieve the same effect, you need to implement the "lazy" behavior yourself.
if isFoo
{
foo()
}
else
{
bar()
}
or more simply:
isFoo ? foo() : bar()
Swift has lazy creation . That is, you can say that variables should not be created until they are used.
In Objective-C, this would require a developer to manually implement this behavior:
@property (nonatomic, strong) NSMutableArray *players;
- (NSMutableArray *)players
{
if (!_players)
{
_players = [[NSMutableArray alloc] init];
}
return _players;
}
This is much easier in Swift and is achieved with the keyword lazy
:
lazy var players = [String]()
source to share