OpenFeature Swift Provider
Introduction
The OpenFeature Swift Provider is intended to be used in combination with the OpenFeature Swift SDK in Apple platform applications. The provider wraps the ConfigDirector Swift SDK.
| Platform | Minimum |
|---|---|
| iOS / iPadOS | 15.0 |
| macOS | 12.0 |
| tvOS | 15.0 |
| watchOS | 8.0 |
Building it requires Swift 6.0 or newer and version 0.6.0 or newer of the OpenFeature Swift SDK. The provider is Sendable, so it can be registered from any task or actor.
Config evaluation is synchronous and reads config state the provider already holds in memory, which is what makes it safe to call from a SwiftUI body. Telemetry about those evaluations is aggregated and reported on its own task, so evaluating a config never waits on the network.
Installation
The provider is distributed through Swift Package Manager from its repository: https://github.com/ConfigDirector/configdirector-swift-openfeature-provider
The ConfigDirector Swift SDK is included as a transitive dependency. The OpenFeature Swift SDK has to be added alongside the provider, since your application imports it to evaluate flags.
# In Xcode, go to File -> Add Package Dependencies... and enter the package URL:
https://github.com/ConfigDirector/configdirector-swift-openfeature-provider
dependencies: [
.package(url: "https://github.com/ConfigDirector/configdirector-swift-openfeature-provider", from: "1.6.0"),
.package(url: "https://github.com/open-feature/swift-sdk", from: "0.6.0"),
],
targets: [
.target(
name: "YourTarget",
dependencies: [
.product(name: "ConfigDirectorOpenFeatureProvider", package: "configdirector-swift-openfeature-provider"),
.product(name: "OpenFeature", package: "swift-sdk"),
]
),
]
Configure and initialize the client
- Create an instance of the provider using your client SDK key. You can retrieve a client SDK key for each environment under
SDK keysin the dashboard's navigation panel. - Set the OpenFeature provider, along with the initial evaluation context.
- Get a client instance from OpenFeature.
import ConfigDirectorOpenFeatureProvider
import OpenFeature
let provider = try ConfigDirectorProvider(clientSDKKey: "YOUR-CLIENT-SDK-KEY")
await OpenFeatureAPI.shared.setProviderAndWait(
provider: provider,
initialContext: ImmutableContext(targetingKey: "user-123")
)
let client = OpenFeatureAPI.shared.getClient()
The initializer throws a ConfigDirectorError only for a programming error, never for a runtime condition: missingClientSDKKey when the key is blank outside offline mode, invalidBaseURL when a custom base URL is not absolute, valuesRequireOfflineMode when values are given outside offline mode, and invalidOfflineValue when one of those values cannot be served. Connection failures are not thrown.
setProviderAndWait returns once the initial config state arrives or the configured timeout elapses. When it times out, the provider reports the error status and keeps connecting in the background, then reports ready as soon as config state arrives. Until then, flags resolve to their default values.
Most applications register the provider once during startup and let it live for the lifetime of the app. In a SwiftUI app that usually means doing so from the App:
import ConfigDirectorOpenFeatureProvider
import OpenFeature
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.task {
guard let provider = try? ConfigDirectorProvider(clientSDKKey: "YOUR-CLIENT-SDK-KEY") else { return }
await OpenFeatureAPI.shared.setProviderAndWait(
provider: provider,
initialContext: ImmutableContext(targetingKey: "user-123")
)
}
}
}
}
connection options of the Swift SDK to manage that yourself instead.Additional configuration options
Additional configuration options can be passed into the provider as ConfigDirectorClientOptions in the optional second argument of the initializer. The types that configure the underlying client are exported from the provider's module, so configuring it needs no second import.
For example, the metadata can be provided like this:
import ConfigDirectorOpenFeatureProvider
let provider = try ConfigDirectorProvider(
clientSDKKey: "YOUR-CLIENT-SDK-KEY",
options: ConfigDirectorClientOptions(
metadata: ConfigDirectorMetaContext(
appName: "YOUR-APP-NAME",
appVersion: "1.0.2"
)
)
)
The provider accepts the same metadata, connection, caching and logger options as the Swift SDK client, refer to the additional configuration options section of the Swift SDK for a full list.
That includes running without a connection: created with ConfigDirectorProvider(options:), the connection mode set to .offline and no client SDK key, the provider serves the values you give it without connecting to ConfigDirector, setProviderAndWait returns at once with the provider ready, and creating it throws when those values cannot be used. The provider's module exports ServedValue, the type of those values.
Values kept on the device
By default, the provider keeps the last values it received from ConfigDirector on the device, in the app's UserDefaults, and serves them on the next launch of the same context until live values arrive. An app opened without a network, after at least one successful connection, resolves flags to the values ConfigDirector last sent instead of the default values passed to the OpenFeature client.
Registering the provider still waits for live values or the connection timeout: setProviderAndWait returns after the timeout as it does without kept values, and the provider then reports the stale status, with a stale event, while it serves the kept values. It reports stale from the moment the kept values are loaded, and again right after the error event a timeout reports. Once live values arrive, the provider reports ready with a ready event and the kept values are replaced. A context change that cannot connect reports reconciling, an error and then stale again, and keeps serving the current values. Flags resolved from the kept values report the CACHED reason.
The values are kept for the context they were evaluated for, and served on the next launch only when the evaluation context has the same kind and targeting key. A context without a targeting key matches on the same install, as long as the app has not been uninstalled, because ConfigDirector derives its identifier from the instance ID the SDK stores; such a context keeps its percentage rollout bucket for as long as that instance ID lasts. Other attributes take no part in the match: live values correct them within a second when there is a network. A context change keeps serving the current values until the new context's values arrive, as it does with live values.
Turn it off, or supply your own store, with the caching option of ConfigDirectorClientOptions, which takes the same CachingOptions the Swift SDK takes: enabled, defaulting to true, and provider, a CachingProvider with read(), write(_:), remove() and sizeLimit() in bytes, defaulting to the app's UserDefaults under a key derived from the client SDK key with a size limit of 256 KB. The provider's module exports both types. The entry is one string whose format belongs to the SDK and may change between SDK versions. An entry above the size limit is removed with one warning, a store that fails is logged once and never stops the provider, and nothing is kept in .offline mode.
let provider = try ConfigDirectorProvider(
clientSDKKey: "YOUR-CLIENT-SDK-KEY",
options: ConfigDirectorClientOptions(
caching: CachingOptions(enabled: false)
)
)
Shut down
The OpenFeature Swift SDK does not shut providers down. The provider closes its connection, and reports whatever telemetry is left, when it is released, which happens after OpenFeatureAPI.shared.clearProvider() as long as you hold no other reference to it. To close it while you still hold one, call provider.close(). The provider cannot be used afterwards.
Retrieve config values
To retrieve config values, use the OpenFeature client:
let booleanValue = client.getBooleanValue(key: "my-config-key", defaultValue: false)
let stringValue = client.getStringValue(key: "my-string-config-key", defaultValue: "Default")
Each OpenFeature getter maps to a ConfigDirector config type:
| OpenFeature getter | ConfigDirector config value |
|---|---|
getBooleanValue | Boolean |
getStringValue | String or enum |
getIntegerValue, getDoubleValue | Number |
getObjectValue | JSON object or JSON array |
getIntegerValue takes and returns an Int64, as the OpenFeature Swift SDK defines it. getObjectValue returns the parsed JSON as an OpenFeature Value, a .structure for a JSON object or a .list for a JSON array:
let settings = client.getObjectValue(key: "my-json-config-key", defaultValue: .structure([:]))
let theme = settings.asStructure()?["theme"]?.asString()
For additional information regarding the OpenFeature client refer to the OpenFeature Swift SDK documentation.
Evaluation details
The detailed getters of the OpenFeature client, such as getBooleanDetails, report why an evaluation produced the value that it did:
| Outcome | Reason | Error code |
|---|---|---|
| A value was found | TARGETING_MATCH | |
| A value kept on the device was served | CACHED | |
| The config carries no value | DEFAULT | |
| The config key is unknown | error | .flagNotFound |
| No config state has arrived yet | error | .providerNotReady |
| The value does not match the requested type | error | .typeMismatch |
When a value was found or served from the values kept on the device, the variant is the name of the variation served, such as treatment, when the config has variations and that variation has a name. Otherwise it is ConfigDirector's ID for the value served, a stable hash you can send to analytics in place of the value itself. Before version 1.6.0 of the provider, the variant was always the value ID, so if you send it to an analytics tool, an experiment's evaluations now show up under the variation names. In every other case the in-code default value is returned.
To report an experiment to an analytics tool, follow the page for Amplitude, Mixpanel, Google Analytics 4, Segment or PostHog, which names the event that tool reads.
From version 1.6.0 of the provider, each evaluation it reports also says which variation was served and which percentage rollout and share served it. That is how ConfigDirector counts the contexts each variation of an experiment reached.
let details = client.getBooleanDetails(key: "my-config-key", defaultValue: false)
if details.errorCode == .providerNotReady {
// No config state has arrived yet, so details.value is the in-code default value.
}
getObjectValue with a structure or a list as the in-code default value resolves to the config's value only when its JSON has that shape. For JSON of another shape you receive the in-code default value with the error code .typeMismatch. ConfigDirector receives that read with the reason type-mismatch, and it counts towards the Config type mismatch alert, which names the requested type as JSONObject or JSONArray.
Reading configs in SwiftUI
The getters are synchronous and make no network calls, so they are safe to call directly from a body. That gives you the current value, but the view will not re-render on its own when the value changes.
To have the view follow a config, re-read it whenever the provider publishes an event. OpenFeatureAPI.shared.observe() is a Combine publisher of provider events that replays the provider's current status to a new subscriber, so the view reads the current value as soon as it appears, and again after every change:
import OpenFeature
import SwiftUI
struct DarkModeToggle: View {
@State private var isOn = false
var body: some View {
Toggle("Dark mode", isOn: $isOn)
.onReceive(OpenFeatureAPI.shared.observe().receive(on: DispatchQueue.main)) { _ in
isOn = OpenFeatureAPI.shared.getClient().getBooleanValue(key: "dark-mode", defaultValue: false)
}
}
}
Update the context
await OpenFeatureAPI.shared.setEvaluationContextAndWait(
evaluationContext: ImmutableContext(
targetingKey: "12345", // In OpenFeature, the targeting key represents the context's identifier
structure: ImmutableStructure(attributes: [
"name": .string("Example User"),
// Any arbitrary traits which can be referenced in targeting rules
"traits": .structure(["region": .string("North America")]),
])
)
)
To evaluate flags for an entity other than a user, such as a tenant, set the context kind with a top-level kind attribute:
await OpenFeatureAPI.shared.setEvaluationContextAndWait(
evaluationContext: ImmutableContext(
targetingKey: "acme",
structure: ImmutableStructure(attributes: [
"kind": .string("tenant"),
"name": .string("Acme Inc."),
"traits": .structure(["plan": .string("enterprise")]),
])
)
)
Leaving kind out means user. A kind inside traits is an ordinary trait, not the context kind. A context kind is 1 to 64 lowercase letters, digits, dashes, or underscores. A context with an invalid context kind is ignored: the SDK logs an error, and flags still resolve successfully, as if no context had been given. Context kinds are available from version 1.3.0 of the provider.
The evaluation context maps onto the ConfigDirector context as follows:
| OpenFeature evaluation context | ConfigDirector context |
|---|---|
The targeting key, or otherwise an id attribute | id |
The top-level kind attribute | kind |
The name attribute | name |
The traits structure attribute | traits |
The boolean anonymous attribute | anonymous |
Any other attribute is ignored. Put the values your targeting rules depend on inside traits.
Awaiting
setEvaluationContextAndWait will wait until the new config values are downloaded or the connection times out. In the case of a timeout, the provider will continue to attempt to connect with the new context in the background.For additional information regarding the OpenFeature client refer to the OpenFeature Swift SDK documentation.
Track events
The provider implements OpenFeature's tracking API. client.track reports to ConfigDirector that something happened in your application, such as a completed checkout, and ConfigDirector shows it on the Live feed and counts it for each variation of a running experiment; see Tracked events.
let client = OpenFeatureAPI.shared.getClient()
client.track(
key: "checkout-completed",
details: ImmutableTrackingEventDetails(
value: 49.9,
structure: ImmutableStructure(attributes: ["plan": .string("pro"), "seats": .integer(3)])
)
)
client.track(key: "tutorial-skipped")
The value of the tracking event details is sent as the event's value, and their attributes as the event's details. The event is reported for the context flags are currently evaluated against, with its targeting key, or otherwise its id attribute, and its kind. While a context change is in flight, that is still the previous context.
An event counts for an experiment only when that context has the targeting key the experiment's flag was evaluated with. Without one, the event is still reported and counts for no experiment. For a context marked anonymous, the event is reported without the targeting key, so it counts for no experiment either.
The provider sends tracked events as the Swift SDK does, with the same limits. A .date attribute is sent as ISO 8601 text in UTC and a number that is not finite as null. Before version 1.6.0 of the provider, a track call did nothing.
Events
The provider publishes its events through OpenFeatureAPI.shared.observe(). It emits configurationChanged whenever configs are updated on the dashboard or via the admin API, carrying the keys of the configs in the update:
import Combine
import OpenFeature
let subscription = OpenFeatureAPI.shared.observe().sink { event in
switch event {
case let .configurationChanged(details):
print("Configs updated: \(details?.flagsChanged ?? [])")
case .ready:
print("Config state is available")
case let .error(details):
print("ConfigDirector could not be reached: \(details?.message ?? "")")
default:
break
}
}
It emits ready when the initial config state arrives after setProviderAndWait has already returned, error when the initial connection times out, stale while the values kept on the device are served, and reconciling followed by contextChanged around a context update.
Test your code
Code that reads flags through OpenFeature is tested by swapping the provider, so it never has to change for a test. The OpenFeature Swift SDK ships no in-memory provider yet, so this provider accepts a test client from the Swift SDK's ConfigDirectorTesting product instead: the SDK's real client connected to an in-memory server your test controls. The provider then resolves every flag from the values the test sets, opens no network connection, and sends no telemetry.
Swift Package Manager exposes only the products of packages your target declares, so add the ConfigDirector Swift SDK to your test target alongside the provider:
dependencies: [
.package(url: "https://github.com/ConfigDirector/configdirector-swift-openfeature-provider", from: "1.6.0"),
.package(url: "https://github.com/ConfigDirector/configdirector-swift-sdk", from: "1.11.0"),
.package(url: "https://github.com/open-feature/swift-sdk", from: "0.6.0"),
],
targets: [
.testTarget(
name: "YourAppTests",
dependencies: [
"YourApp",
.product(name: "ConfigDirectorTesting", package: "configdirector-swift-sdk"),
]
),
]
In an Xcode project, add the configdirector-swift-sdk package and link its ConfigDirectorTesting library to your test target under Frameworks and Libraries.
The initializer that takes a client is init(injectedClient:), and it is visible only to files that import the provider with @_spi(Testing), which keeps it out of application code:
import ConfigDirectorTesting
@_spi(Testing) import ConfigDirectorOpenFeatureProvider
import OpenFeature
import Testing
struct CheckoutTests {
@Test func showsTheNewCheckout() async {
let testClient = makeTestClient(values: ["new-checkout": true, "max-items": 20])
defer { testClient.client.close() }
await OpenFeatureAPI.shared.setProviderAndWait(
provider: ConfigDirectorProvider(injectedClient: testClient.client),
initialContext: ImmutableContext(targetingKey: "user-123")
)
let client = OpenFeatureAPI.shared.getClient()
#expect(client.getBooleanValue(key: "new-checkout", defaultValue: false))
#expect(client.getIntegerValue(key: "max-items", defaultValue: 0) == 20)
testClient.setValue(false, for: "new-checkout")
#expect(!client.getBooleanValue(key: "new-checkout", defaultValue: false))
}
}
OpenFeatureAPI.shared is one global, so tests that register their own provider on it cannot run in parallel. When the code under test takes an OpenFeatureAPI or a Client rather than reading the shared instance, create an OpenFeatureAPI() per test instead.
The test client's controls are the same as with the Swift SDK: setValue(_:for:), removeValue(for:), replaceValues(_:), the initialization and context update holds and failures, contextUpdates and trackedEvents. The Swift SDK's testing section describes each of them and the values they take. Through the provider:
setValuemakes the OpenFeature client resolve the new value at once and the provider emitconfigurationChangedwith that key;removeValuemakes the flag resolve to its default value.- The provider initializes the client when it is registered and updates the client's context whenever the evaluation context changes, as it does with a client it creates itself. A test client that was already initialized therefore reconnects on registration, and its
contextUpdatesrecords the provider's context after the test's own. holdInitialization()before registering keepssetProviderAndWaitwaiting, with the providernotReadyand flags at their default values, untilcompleteInitialization()or the test client'stimeoutelapses. A timed-out or failed initialization (failInitialization()) makes the provider report theerrorstatus, as a connection failure would, and flags resolve to their default values.- An event tracked through OpenFeature shows up in
trackedEventswith the test client's current context. Its value is a.double, as OpenFeature's Swift SDK defines it, and its attributes are itsdetails. - The provider never closes a client it was given, whether through
close()or when it is released. Close the test client'sclientwhen the test is done, as in the example.