Skip to main content
Version: Config V1 (legacy)

OpenFeature Provider for Swift

CI

ConfigCat OpenFeature Provider for Swift on GitHub

Getting started

1. Install the provider

Swift Package Manager

If you manage dependencies through SPM, in the dependencies section of Package.swift add:

.package(url: "https://github.com/configcat/openfeature-swift", from: "0.1.0")

and in the target dependencies section add:

.product(name: "ConfigCat", package: "openfeature-swift"),

Xcode Dependencies

  • Open the dependencies dialog from File > Add Package Dependencies...
  • Search for https://github.com/configcat/openfeature-swift and click Add Package.

2. Initialize the provider

The initializer of ConfigCatProvider takes the SDK key and an optional ConfigCatOptions argument containing the additional configuration options for the ConfigCat Swift SDK:

import ConfigCatOpenFeature
import ConfigCat
import OpenFeature

Task {
// Configure the provider.
let provider = ConfigCatProvider(sdkKey: "<YOUR-CONFIGCAT-SDK-KEY>") { opts in
opts.pollingMode = PollingModes.autoPoll()
}

// Configure the OpenFeature API with the ConfigCat provider.
await OpenFeatureAPI.shared.setProviderAndWait(provider: provider)

// Create a client.
let client = OpenFeatureAPI.shared.getClient()
}

For more information about all the configuration options, see the Swift SDK documentation.

3. Evaluate your feature flag

let isAwesomeFeatureEnabled = client.getBooleanValue(key: "isAwesomeFeatureEnabled", defaultValue: false)
if isAwesomeFeatureEnabled {
doTheNewThing()
} else {
doTheOldThing()
}

Evaluation Context

An evaluation context in the OpenFeature specification is a container for arbitrary contextual data that can be used as a basis for feature flag evaluation. The ConfigCat provider translates these evaluation contexts to ConfigCat User Objects.

The following table shows how the different context attributes are mapped to User Object attributes.

Evaluation contextUser ObjectRequired
targetingKeyidentifier
Emailemail
Countrycountry
Any othercustom

To evaluate feature flags for a context, use the setEvaluationContext() method on OpenFeatureAPI.shared to set the context for the provider:

let context = MutableContext(targetingKey: "#SOME-USER-ID#", structure: MutableStructure(attributes: [
"Email": Value.string("[email protected]"),
"Country": Value.string("CountryID"),
"Rating": Value.double(4.5),
"Roles": Value.list([Value.string("Role1"), Value.string("Role2")])
]))
OpenFeatureAPI.shared.setEvaluationContext(evaluationContext: context)

Look under the hood