> On Apr 13, 2016, at 10:08 AM, Erica Sadun <[email protected]> wrote: > > >> On Apr 13, 2016, at 8:25 AM, Sean Heber via swift-evolution >> <[email protected]> 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 _______________________________________________ swift-users mailing list [email protected] https://lists.swift.org/mailman/listinfo/swift-users
