Does Swift have an equivalent Kotlin `with` function?

In Kotlin we could change 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
}

However, in Swift, as shown below, do I have an equivalent function withto use?

// Original code
var commonObj = ClassCommonObj()
 commonObj.data1 = dataA
 commonObj.data2 = dataB
 commonObj.data3 = dataC
+6
source share
1 answer

Unfortunately, such a function is not yet available in Swift. However, similar functionality can be achieved using the extension capabilities:

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

This protocol and extension provides two functions inlinewhere you can return a processed object, and the other is strictly similar to withKotlin and other languages ​​(Visual Basic was supported in the 90s).

Using

Specify the types to which these functions should apply:

extension NSObject: ScopeFunc {} 

apply

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

Here we create the object, and as soon as the closure is done, the changed object is returned.

with

imageView.with {
    $0.isHidden = true
}

with .

.

:

Swift , , . , - @inline (__always). , , , inlining - .

+5

Source: https://habr.com/ru/post/1690107/


All Articles