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
}

      

+3


source to share


3 answers


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)()
}

      

+4


source


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]()

      

+1


source


I found a very simple solution following leo's answer

func foo(a: Int)() {
  println("this is foo")
}

func bar(b: Int)() {
  println("this is bar")
}

func maybeFooOrBar(isFoo: Bool) {
  let myFoo = foo(1)
  let myBar = bar(2)
  isFoo ? myFoo() : myBar()
}

      

0


source







All Articles