A Blog

Private Extensions in Swift

December 11, 2015

Here’s a quickie. In Swift, the default accessor for strcutures is internal, meaning that it is available to everything else within the module. You can change this by adding private or public in front of them like so:

private class Foo {

private means that the construct is only available within the same file. I just “discovered”1 that you can also mark an Extension as private, which I hadn’t considered before. This let’s you add functionality to a struct or class that may be useful in the current context of everything within that same file, but doesn’t make sense elsewhere.

For example, in a HealthKit project you may be only dealing with fluid ounces for an HKQuantitySample and converting all the time is a bit of a pain. You don’t necessarily want to make a quantityInOunces computed variable available on the whole app, but in a specific file where you’re computed all those ounces, it makes sense.

private extension HKQuantitySample {
	var quantityInOunces: Double? { /* blah */ }

class HealthKitManager {
	func doStuff() {
		// Calculate a bunch of ounces easy peasy.
  1. Couldn't think of a better word, but yeah I'm regular Vasco de Gama.

Scott Williams

Written by Scott Williams who lives and works in sunny Phoenix, AZ. Twitter is also a place.