[swift-users] [swift-evolution] What about a VBA style with Statement?

Erica Sadun erica at ericasadun.com
Wed Apr 13 10:33:39 CDT 2016


> On Apr 13, 2016, at 9:26 AM, Sean Heber <sean at fifthace.com> wrote:
> 
>> On Apr 13, 2016, at 10:08 AM, Erica Sadun <erica at ericasadun.com> wrote:
>> 
>> 
>>> On Apr 13, 2016, at 8:25 AM, Sean Heber via swift-evolution <swift-evolution at swift.org> wrote:
>>> 
>>> This pair works pretty well, too, if you don’t mind free functions:
>>> 
>>> func with<T>(inout this: T, @noescape using: inout T->Void) { using(&this) }
>>> func with<T>(this: T, @noescape using: T->Void) { using(this) }
>>> 
>>> It works either with classes or mutable structs if you call it correctly and the type doesn’t matter.
>>> 
>>> l8r
>>> Sean
>> 
>> My current version is this:
>> 
>> func with<T>(item: T, @noescape update: (inout T) -> Void) -> T {
>>    var this = item; update(&this); return this
>> }
>> 
>> Used, for example:
>> 
>> struct Foo { var (a, b, c) = ("a", "b", "c") }
>> class Bar: DefaultReflectable { var (a, b, c) = ("a", "b", 2.5) }
>> var f = with(Foo()) { $0.a = "X" }
>> var b = with(Bar()) { $0.a = "X" }
>> print(f) // Foo(a: "X", b: "b", c: "c")
>> print(b) // Bar(a=X, b=b, c=c)
>> 
>> Is there an advantage to having a pair of functions?
> 
> I don’t know if it’s a huge advantage or not, but with warnings on unused results, using a with() that has a return with a class instance would mean you’d have to discard the return result explicitly or pointlessly reassign the results to your instance (thus meaning not using a let) just to avoid the warning. If you annotated the with() to allow discarding the result, then it’d be error-prone for structs. It seemed “safer” to me to have a pair.
> 
> l8r
> Sean
> 

If you want to call

>> let f = with(Foo()) { $0.a = "X" }
>> let b = with(Bar()) { $0.a = "X" }

with constant assignment and an initializer, I'm not sure how yours would work. Could they?

-- E, trying right now in the playground



More information about the swift-users mailing list