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 - .