Private Extensions in Swift

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:

1
2
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.

1
2
3
4
5
6
7
8
9
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.

Tags: code,, swift

Copyright © 2017 - Scott Williams - Powered by Octopress