[swift-evolution] [Discussion] "with" statement/method
Vladimir.S
svabox at gmail.com
Fri Apr 22 07:37:46 CDT 2016
On 22.04.2016 14:02, Joanna Carter wrote:
> As much as I detested the 'with' construct in Delphi, with all its
accompanying opportunities for errors of scope, if you really think it a
good idea, then you need to consider the possibility of those who want to
'with' more than one target. In which case, the use of $0, $1, etc would
seem logical, although not necessarily very readable.
>
> Joanna
>
> --
> Joanna Carter
> Carter Consulting
>
> (de mon iPhone)
>
Actually we can "manually" now implement the very clean and handy "with"
(including with more than 1 "target") like this:
(I propose to include such kind of "with" feature to language or to
standard classes/protocols to be able to use it out-of-box for any
class/structure, not for some we have to apply manually)
class A {
var x = 0
var y = 0
var z = 0
func with(block: (this: A)->()) -> Self {
block(this: self)
return self
}
func with<T>(another: T, block: (this: A, that: T)->()) -> Self {
block(this: self, that: another)
return self
}
}
var myFirstVeryLongInstanceName = A().with {
$0.x = 1
$0.y = 2
$0.z = 3
}
var mySecondVeryLongInstanceName = A().with {new in
new.x = 11
new.y = 12
new.z = 13
}
myFirstVeryLongInstanceName.with {my in
my.x *= 1
my.y *= 2
my.z *= 3
}
mySecondVeryLongInstanceName.with(myFirstVeryLongInstanceName) {to, from in
to.x = from.x * 10
to.y = from.y * 20
to.z = from.z * 30
print(from.x)
print(to.x)
}
mySecondVeryLongInstanceName.with(myFirstVeryLongInstanceName) {
$0.x = $1.x * 100
$0.y = $1.y * 200
$0.z = $1.z * 300
print($1.x)
print($0.x)
}
More information about the swift-evolution
mailing list