[swift-evolution] Customized Inline Init Closure

Weston Catron wcatron at catrondevelopment.com
Sun Jan 3 00:37:03 CST 2016

Ability to write an initializer while initializing an object.


let name = “John Apple”;
let person = Person {
    self.name = nameInput.first() + " " + nameInput.last()
    self.dob = dateInput.datetime()
    If (self.age() > 18) {
        self.taxableStatus = INDEPENDANT
    } else {
        self.taxableStatus = DEPENDANT

Helpful examples: Objects with many required parameters that are defaulted in the initializers. 


let label = SKLabelNode(text: "Example") 
label.position = CGPoint(x: 0, y: 250); 
label.fontSize = 34; 
label.fontColor = UIColor.blackColor() 

Can become:

let label = SKLabelNode(text: self.package!.title) {
    self.position = CGPoint(x: 0, y: 250)
    self.fontSize = 34
    self.fontColor = UIColor.blackColor() 

Readability Instead of a large amount of code setting up temporary variables to pass into an initializer, all initializing code could be wrapped in a closure.

Flexibility Instead of exhaustive initializers covering many use cases. Simpler initializers can be extended as needed. This can also encourage required properties over optional ones that are immediately defined. 

Compiler Warnings Closures react the same as initializers within classes, warning users of incomplete implementation of required properties.

Possible disadvantages:

Sloppy Coding Instead of writing complete initializers programmers can just rely on in-line initializers.  

Tried Before I found this feature is also available in C# (https://msdn.microsoft.com/en-us/library/bb397680.aspx <https://msdn.microsoft.com/en-us/library/bb397680.aspx>). Not sure if it was helpful then but many languages since don't appear to use it. 

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

More information about the swift-evolution mailing list