ios - Swift 对 Java 的 Runnable 的模拟

标签 ios swift

令人惊讶的是,谷歌搜索没有返回任何相关信息。 我在 Android 上做什么:

void doSomethng(Runnable r){
r.run();
}

这只是在发送类的上下文中传递一些代码块,然后按需执行该 block 。 如何使用适用于 iOS 的 Swift 执行相同的操作?

最佳答案

获取没有参数且没有返回值的 block 的函数语法如下:

func doSomethng(runnable: () -> ()){
   runnable()
}

如果你打算广泛使用这样的 block ,你可以为它定义一个特殊的类型:

typealias Runnable = () -> ()

func doSomethng2(runnable: Runnable){
    runnable()
}

我还建议您查看此站点 fuckingclosuresyntax.com快速了解 Swift 中 block /闭包的语法。

如果您需要在单独的线程中运行 block 检查GCD

关于ios - Swift 对 Java 的 Runnable 的模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39203203/

相关文章:

swift - 从自定义原型(prototype)单元格中的 UIButton PrepareForSegue

ios - 超出范围,线程问题

ios - 将渐变应用于 UIImage - 如何去除颜色反转?

ios - 带有自定义声音的 UNMutableNotificationContent

iphone - 我的倒计时方法有什么问题?

ios - Collection View Controller 未添加为 subview

ios - Swift 中开关盒的详尽条件

ios - 在 UITableViewController 和带有 TableView 的 UIViewController 之间切换

ios - 如何在 TableView Cell 中创建长按按钮以进行 segue

ios - Swift:ScrollRectToVisible 不工作