android - Swift 4 等效于 Kotlin "anonymous class"表示法

标签 android ios swift kotlin

我用 Kotlin 写了一段时间,我习惯了使用下一个模式:

variable.addSomething(object: TargetType() { ...code... })

var variable = object: TargetType() { ...code... }

(如果我没有遗漏什么)

是否可以在 Swift 中以某种方式使用这种模式?它怎么称呼? :)

编辑: 我真正想做的是 - 将预配置的 RxSwift.SingleEvent 存储在对象内部的 let/var 中,并在以后多次重用它。

在代码中,正如我想象的那样,它应该是这样的:

private var observer = SingleEvent<Response>(ok_callback, error_callback) { 
      override success(el: Element) {
             ok_callback(el)
             super.success(el)
    }
      override error(er: Error) {
           self.onErrorRetry(er, callback)
    }
}

如果在一些神奇的工作后重试 - 只需调用我的回调并返回:)

最佳答案

它似乎是尾随闭包。改编自 Swift programming language - Closures :

If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is written after the function call’s parentheses, even though it is still an argument to the function. When you use the trailing closure syntax, you don’t write the argument label for the closure as part of the function call.

让我们编写代码:

简单地说,你所要做的就是创建一个函数,它的最后一个参数是一个闭包:

func doSomething(firstParameter: Any, closure: () -> Void) { }

因此你可以称它为:

doSomething(firstParameter: "whatever") {
    // ...
}

这里没有什么特别的,如果它是函数签名中的最后一个参数,它是 Swift 语言的一个很酷的功能,可以“跟踪”闭包 参数。

在初始化的情况下,几乎是一样的:

struct MyObject {
    init(firstParameter: Any, closure: () -> Void) { }
}

let variable = MyObject(firstParameter: "whatever") {  }

当然,此模式之后还有许多其他语言功能,但这里是字典的 merge 方法的示例,您可以认识到如何以多种方式键入它如以下答案中所述:Map Dictionary Keys to add values - Swift .


更新:

如果您的目标是将其用作常量/变量——例如传递给函数——,您可以这样做:

let variable: (String) -> Void = { name in
    print("The name is: \(name)!")
}

在这一点上,variable 类型是(String) -> Void 这意味着它是一个可以传递到其他地方的常量;考虑以下方法:

func doSomething(closure: (String) -> Void) {
    closure("Nikita")
}

因为 doSomething 接受类型为 (String) -> Void 的参数,你可以这样做:

doSomething(closure: variable) // The name is: Nikita!

而不是称它为:

doSomething { name in
    print("The name is: \(name)!")
}

这会阻止样板代码。

关于android - Swift 4 等效于 Kotlin "anonymous class"表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51612914/

相关文章:

Android sp vs dp 文本 - 什么会调整 'scale' 以及支持的理念是什么

objective-c - UIAlertView 显示一次

ios - UICollectionView 布局,带有搜索栏的节标题和标题的另一个动态节标题

java - 如何重新检查 android-saripaar 中的字段?

android - 找不到类 com.google.android.gms.location.LocationClient (android)

ios - Facebook graph API将多张照片发布到相册和提要

ios - 您可以多次设置 contentInset 吗?

ios - 无法构建包含 Objective-C Tesseract 库的 Swift 应用程序

ios - Swift WKWebView 与 Javascript 交互

java - 单击抽屉导航上的字符串/链接可加载本地 HTML 页面