[swift-evolution] Removal of dispatch_once() in Swift 3?

Joe Groff jgroff at apple.com
Fri Jun 17 11:30:21 CDT 2016


> On Jun 16, 2016, at 11:32 AM, Charlie Monroe via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hard to say without full code, but the following code compiles just fine in Xcode 8:
> 
> class FloorPlatonicGeometryAndMaterial {
> 	init(modelDirectory: NSURL) throws {
> 		/// ...
> 	}
> }
> 
> class PlatonicPieceOfFurniture {
> 	internal var modelDirectoryURL: URL
> 	
> 	var floorGeometryAndMaterial: FloorPlatonicGeometryAndMaterial {
> 		return self.floorGeometryAndMaterialBacking!
> 	}
> 	
> 	private lazy var floorGeometryAndMaterialBacking: FloorPlatonicGeometryAndMaterial? = 
> 				try! FloorPlatonicGeometryAndMaterial(modelDirectory: self.modelDirectoryURL)
> 	
> 	init(modelDirectoryURL: URL) {
> 		self.modelDirectoryURL = modelDirectoryURL
> 		/// ...
> 	}
> }
> 
> All lazy initialization pretty much uses dispatch_once. Also remember, that your code can be as followed:
> 
> private lazy var stringValue: String? = {
> 	var str = self.description
> 	str += "\n"
> 	...
> 	return str
> }()
> 
> lazy var initialization doesn't have to be a one-liner, but can be an applied closure.

`lazy var` does *not* use dispatch_once, so it isn't thread-safe without synchronization. Only global and static properties are initialized with a dispatch_once-like mechanism.

-Joe


More information about the swift-evolution mailing list