Does Swift have an implicit Object Initializer, like in C#?

Swift doesn't have such feature.

You can implement similar interface using closure, but...

class MyClass {
    var name = ""
    var style = 0
    init(initializer:((MyClass)->Void)? = nil) {
        initializer?(self)
    }
}

let a = MyClass2() {
    $0.name = "foo"
    $0.style = 2
}

There is no implicit self here, instead, you have to use implicit closure parameter $0.


Not as such. If you create a custom struct, Swift will, under certain conditions, create a default memberwise initializer that is close to what you're looking for. But otherwise, I don't think there's even a way to implement such a feature, since Swift lacks anything like a with keyword that would get you into the new instance's scope.

Update: this is as close as I can get, by defining a custom operator:

infix operator <| { }

func <|<T>(decl: @autoclosure () -> T, f: T -> () ) -> T {
    let obj = decl()
    f(obj)
    return obj
}

let label = UILabel() <| {
    $0.frame = CGRect(x: 10, y: 10, width: 300, height: 25)
    $0.text = "Hello"
    $0.enabled = false
}

println(label)
// <UILabel: 0x7fb46240b210; frame = (10 10; 300 25); text = 'Hello'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x7fb46240c2b0>>

Tags:

Swift