[swift-evolution] [Proposal] Allow optional binding of instance variables in constructors

Taras Zakharko taras.zakharko at uzh.ch
Mon Apr 11 02:31:31 CDT 2016


One place where I find myself using the guard statement a lot is state initialisation. E.g. in init()

guard let
           device   = MTLCreateSystemDefaultDevice(),
           library  = device.newDefaultLibrary()
else {
   fatalError(“Could not initiallize Metal, aborting”)
}

Here, the two variables device and library are intended to be instance variables of an engine backbone system. However, because optional binding in guard can only introduce new local statements, one needs to add additional boilerplate in the end, e.g.:

self.device = device
self.library  = library

What I want to propose is a very simple QOL enhancement: allow optional binding to be used with instance variables in the constructors. If the binding fails, the instance construction cannot proceed (the relevant scope is the instance). The syntax would be 

guard  device   = MTLCreateSystemDefaultDevice(),
           library  = device.newDefaultLibrary()
else {
   fatalError(“Could not initiallize Metal, aborting”) // or return nil
}


Few notes:

- This would only apply to guard statement, because binding in the if statement only applies to the internal if scope by definition
- One could also ask for instance optional binding in any context where instance assignment is legal. However, this would make guard inconsistent, as it won’t be able to prevent inconsistent state from being invisible to the app. Therefore its best to restrict this to cases where state is being constructed, and fail the construction if the guard fails (hence init() )

Best, 

 Taras






           
   


More information about the swift-evolution mailing list