Ios swift中的惰性函数计算

Ios swift中的惰性函数计算,ios,swift,if-statement,functional-programming,lazy-evaluation,Ios,Swift,If Statement,Functional Programming,Lazy Evaluation,想知道是否可以懒洋洋地计算一个简单的if语句。下面是一个将打印“this is foo”和“this is bar”的示例,但我确实想让它只打印第一个字符串: func foo() { println("this is foo") } func bar() { println("this is bar") } func maybeFooOrBar(isFoo: Bool) { let myFoo = foo() let myBar = bar() isFoo ? myFo

想知道是否可以懒洋洋地计算一个简单的if语句。下面是一个将打印“this is foo”和“this is bar”的示例,但我确实想让它只打印第一个字符串:

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
}

我找不到规范的证据证明Swift不是一种懒惰的评估语言,但我相信如果我错了,社区会纠正我

因为它不是惰性的,所以方法调用只是按顺序执行,而不是确定永远不需要调用哪些方法

为了达到同样的效果,您需要自己实现“懒惰”行为

if isFoo
{
    foo()
}
else
{
    bar()
}
或者更简单地说:

isFoo ? foo() : bar()

斯威夫特确实有。也就是说,您可以告诉它在使用变量之前不应该实例化它们

在Objective-C中,这将要求开发人员手动实现此行为:

@property (nonatomic, strong) NSMutableArray *players;
- (NSMutableArray *)players 
{
    if (!_players) 
    {
        _players = [[NSMutableArray alloc] init];
    }
    return _players;
}
在Swift中,这要简单得多,使用
lazy
关键字可以实现:

lazy var players = [String]()

不知道这是否是您想要的,您可以将函数用作类型

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()
 }
然后,如果您
callmaybeafoorbar(true)
将打印第一个函数,
callmaybeafoorbar(false)
wii打印第二个函数

而且,这可以通过一种明确的方式来实现

func maybeFooOrBar(isFoo: Bool) {
    (isFoo ? foo : bar)()
}

根据leo的回答,我找到了一个非常简单的解决方案

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

我不明白投反对票的原因。这是一个问得很好的问题。我怀疑这是因为这是不可能的。(我不知道还有什么可以肯定的,我会把它作为一个答案)是的,我知道这个很好用。但是让它像我的例子中那样工作真的很有趣。你问题中的例子的问题是它忽略了函数调用的影响。没有使用结果变量并不意味着函数调用没有执行其他操作-理论上,编译器可以尝试确定函数调用是否可以优化,但是foo()或bar()可以这可能会导致许多额外的函数调用,而且很快就会变得非常困难-对于程序员来说,如果不需要调用函数,那么不调用函数就简单多了。James,您不能将参数传递给延迟var初始化。如果要使大多数函数都是引用透明的,那么这是行不通的。是的,我看到了。但问题是关于惰性函数,而不是惰性变量。打开google或swift文档并找到如何实例化lazy变量是非常简单的。@RudraFury,我只包含了这一点,因为我认为您可能已经阅读了关于lazy实例化的内容,完全忘记了它是什么,然后将其与lazy评估混淆了。。。是的;)