Swift中是否有Kotlin等效的`with`函数? [英] Is there an Kotlin equivalent `with` function in Swift?

查看:75
本文介绍了Swift中是否有Kotlin等效的`with`函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Kotlin, we could change the below

// 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函数要使用?

However in Swift as below, do I have equivalent with function to use?

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

推荐答案

不幸的是,到目前为止,在Swift中还没有这样的功能.但是,借助扩展功能可以实现类似的功能:

Unfortunately, no such functionality so far in Swift. However, similar functionality can be reached with the power of extensions:

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

此协议和扩展提供了两个inline函数,其中一个可以用来返回处理后的对象,另一个严格类似于Kotlin和其他语言中的with(在90年代支持Visual Basic).

This protocol and extension provides two inline functions, where one can be served to return processed object, and the other is strictly similar to with in Kotlin and other languages (Visual Basic supported in 90s).

用法

指定这些功能应应用于的类型:

Specify types which these functions should apply to:

extension NSObject: ScopeFunc {} 

apply :

apply:

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

在这里我们创建一个对象,并在执行完闭包后返回修改后的对象.

Here we create an object and once the closure is executed, modified object is returned.

with :

with:

imageView.with {
    $0.isHidden = true
}

等效于Kotlin中的with.

Works equal to with in Kotlin.

最初基于此源代码.

注意:

通常认为Swift编译器足够聪明,可以决定是否应内联函数.即使没有严格指定@inline (__always),由于它们的相对紧凑性,很可能会内联这两个代码.无论哪种方式,您都应该知道此关键字不会影响逻辑及其结果,因为内联是关于优化该程序.

Swift compiler is generally regarded as smart enough to decide whether or not a function should be inlined. Quite likely, these two would be inlined due to their relative compactness even without strictly specifying @inline (__always). Either way, you should know that this keyword does not affect the logic and the result of these, because inlining is about optimizing the program.

这篇关于Swift中是否有Kotlin等效的`with`函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆