Swift lambda 被插入到参数列表的末尾

标签 swift

使用 Swift 3.1

func foo() {
    { () ->  Void in 
    print("oh, nice, now this works too!!!")
    }()
}
foo()

有效...但是

func foo() {
    print("Hi!")
    { () ->  Void in 
    print("oh, nice, now this works too!!!")
    }()
}
foo()

会导致

ERROR at line 2, col 2: cannot invoke 'print' with an argument list
of type '(String, () -> Void)' 

可以修复打印后插入分号

print("Hi!");

或 lambda 定义周围的括号。但是,我感兴趣的是,从 Swift 编译器的角度来看,行为的根本原因是什么?

最佳答案

在第二种情况下,您需要将 print 调用与 lambda block 分开。

第一种情况:

func foo() { () -> () }

没问题,你可以在闭包中做任何你想做的事

第二种情况:

编译器认为您是在告诉 print 语句在结束后执行您的闭包。

因此您需要用分号分隔您的 print("hi") 语句或将 lambda block 包装起来以使其显式显示。

关于Swift lambda 被插入到参数列表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46935244/

相关文章:

ios - dismissViewControllerAnimated 导致 EXC_BAD_ACCESS - swift

swift - Alamofire 导入失败

ios - 在显示 UIContextMenu 时从 UICollectionView 中删除项目时出现奇怪的动画

ios - mainMixerNode 快速崩溃

ios - RestKit 保留 CoreData 对象

ios - 在 Swift 中迭代并将图像从数组加载到 Collection View Controller 的正确方法

ios - 2 个 View Controller 合二为一( Collection View ?)

ios - 静态方法中的 UIAlertController 给出错误 : extra argument animated in cell

ios - Swift - 检测在 UISearchBar 上输入的文本

ios - 具有SwiftUI和CoreLocation的纯MVVM