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






           
   
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to