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

Erica Sadun erica at ericasadun.com
Wed Apr 13 11:04:56 CDT 2016

> On Apr 13, 2016, at 9:34 AM, Kurt Werle via swift-evolution <swift-evolution at swift.org> wrote:
> I've always thought that the with construct is not a good idea.  It seems to me that the moment you want to use with it indicates that you are getting too much into some other classes business; shouldn't that class deal with this?  Why are you exposing/integrating so much of some other class's logic?  Maybe there should be a method that does all this, or maybe a custom struct that passes all the appropriate information...
> Yeah, there are exceptions - always.  But for the most part I'm not a fan.
> Kurt

The biggest advantage of the with pattern IMO is Cocoa initializers. It provides a more unified 
initialization scope. Instead of:

let questionLabel = UILabel()
questionLabel.textAlignment = .Center
questionLabel.font =  UIFont(name:"DnealianManuscript", size: 72)
questionLabel.text = currentQuestion.text
questionLabel.numberOfLines = 0

You get:

let questionLabel2 = with(UILabel()) {
    $0.textAlignment = .Center
    $0.font =  UIFont(name:"DnealianManuscript", size: 72)
    $0.text = currentQuestion.text
    $0.numberOfLines = 0

You also have the option to customize a Value type before assigning it to a constant or to base
a new value constant on a copy of an existing value constant:

struct Foo { var (a, b, c) = ("a", "b", "c") }
var f = with(Foo()) { $0.a = "X" }
print(f) // Foo(a: "X", b: "b", c: "c")

I personally would love to see a Swift construct that created a scope with `self` defined so the
awkward `$0.` prefixes could be discarded.

-- E, who may have brought up this topic once or twice before on this list

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160413/eb7c7165/attachment.html>

More information about the swift-evolution mailing list