gpt4 book ai didi

swift - Swift 中是否有 Kotlin 等效的 `with` 函数?

转载 作者:IT老高 更新时间:2023-10-28 13:42:04 26 4
gpt4 key购买 nike

在 Kotlin 中,我们可以更改以下内容

// Original code
var commonObj = ClassCommonObj()
commonObj.data1 = dataA
commonObj.data2 = dataB
commonObj.data3 = dataC

// Improved code
var commonObj = ClassCommonObj()
with(commonObj) {
data1 = dataA
data2 = dataB
data3 = dataC
}

但是在下面的 Swift 中,我是否有等效的 with 函数可以使用?

// Original code
var commonObj = ClassCommonObj()
commonObj.data1 = dataA
commonObj.data2 = dataB
commonObj.data3 = dataC

最佳答案

不幸的是,到目前为止,Swift 中还没有这样的功能。然而,类似的功能可以通过扩展的力量来实现:

protocol ScopeFunc {}
extension ScopeFunc {
@inline(__always) func apply(block: (Self) -> ()) -> Self {
block(self)
return self
}
@inline(__always) func with<R>(block: (Self) -> R) -> R {
return block(self)
}
}

这个协议(protocol)和扩展提供了两个inline函数,一个用于返回处理后的对象,另一个与Kotlin和其他语言中的with非常相似( 90 年代支持 Visual Basic)。

用法

指定这些函数应该应用于的类型:

extension NSObject: ScopeFunc {} 

申请:

let imageView = UIImageView().apply {
$0.contentMode = .scaleAspectFit
$0.isOpaque = true
}

这里我们创建一个对象,一旦执行闭包,就返回修改后的对象。

:

imageView.with {
$0.isHidden = true
}

与 Kotlin 中的 with 相同。

最初基于 this source code .

注意:

Swift 编译器通常被认为足够聪明,可以决定是否应该内联函数。很可能,即使没有严格指定 @inline (__always),这两者也会因为相对紧凑而被内联。不管怎样,你应该知道这个关键字不会影响这些的逻辑和结果,因为内联大约是optimizing the program。 .

关于swift - Swift 中是否有 Kotlin 等效的 `with` 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47586520/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com