---
title: "Swift SDK"
description: "Install and configure the Swift SDK, evaluate configs and feature flags, and keep SwiftUI views current as values change"
canonical_url: "https://docs.configdirector.com/sdks/mobile/swift"
---
# Swift SDK

> Install and configure the Swift SDK, evaluate configs and feature flags, and keep SwiftUI views current as values change

<div hidden="true" dataTitleIcon="swift">



</div>

<external-badges repo="configdirector-swift-sdk">



</external-badges>

## Introduction

The Swift SDK is intended to be used by Apple platform applications. It evaluates your configs against a context, keeps them current as they change in the dashboard, and hands SwiftUI values it can re-render from.

<table>
<thead>
  <tr>
    <th>
      Platform
    </th>
    
    <th>
      Minimum
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      iOS / iPadOS
    </td>
    
    <td>
      15.0
    </td>
  </tr>
  
  <tr>
    <td>
      macOS
    </td>
    
    <td>
      12.0
    </td>
  </tr>
  
  <tr>
    <td>
      tvOS
    </td>
    
    <td>
      15.0
    </td>
  </tr>
  
  <tr>
    <td>
      watchOS
    </td>
    
    <td>
      8.0
    </td>
  </tr>
</tbody>
</table>

Building it requires Swift 6.0 or newer. The package is built in Swift 6 language mode under strict concurrency and every public type is `Sendable`, so the client can be shared across tasks and actors without wrapping it.

Config evaluation is synchronous and reads config state the client 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 SDK is distributed through Swift Package Manager from its repository: [https://github.com/ConfigDirector/configdirector-swift-sdk](https://github.com/ConfigDirector/configdirector-swift-sdk)

In Xcode, go to **File → Add Package Dependencies…** and enter the package URL:

```txt
https://github.com/ConfigDirector/configdirector-swift-sdk
```

To add it to a Swift package instead, declare it in `Package.swift`:

```swift [Package.swift]
dependencies: [
    .package(url: "https://github.com/ConfigDirector/configdirector-swift-sdk", from: "1.11.0"),
],
targets: [
    .target(
        name: "YourTarget",
        dependencies: [.product(name: "ConfigDirector", package: "configdirector-swift-sdk")]
    ),
]
```

## Configure and initialize the client

1. Create an instance of the client providing your client SDK key. You can retrieve a client SDK key for each environment under `SDK keys` in the dashboard's navigation panel.
2. Initialize the client to initiate its connection lifecycle.

```swift [ConfigDirectorSetup.swift]
import ConfigDirector

// Creating the client makes no network calls. It throws only for a programming
// error, such as a blank SDK key or a custom base URL that is invalid.
let client = try ConfigDirectorClient(clientSDKKey: "YOUR-CLIENT-SDK-KEY")

// Connects and waits until config values are received, or until it times out.
// After a timeout the client keeps trying to connect in the background.
await client.initialize()
```

The client is thread safe. Create one and share it for the lifetime of the app.

<note>

Before the client is initialized, config values will evaluate to the default value provided in code.

</note>

The initializer throws a `ConfigDirectorError` only for a programming error, never for a runtime condition: `missingClientSDKKey` when the key is blank outside [offline mode](#run-without-a-connection), `invalidBaseURL` when a custom base URL is not absolute, and `valuesRequireOfflineMode` or `invalidOfflineValue` when offline values are given wrongly. Connection failures are not thrown — `initialize` returns normally whether or not config state arrived, and `isReady` tells you which happened.

Most applications create a single client instance, initialize it during startup, and let it live for the lifetime of the app. In a SwiftUI app that usually means owning it in the `App`:

```swift [MyApp.swift]
import ConfigDirector
import SwiftUI

@main
struct MyApp: App {
    @State private var client = try? ConfigDirectorClient(clientSDKKey: "YOUR-CLIENT-SDK-KEY")

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.configDirectorClient, client)
                .task {
                    await client?.initialize(context: ConfigDirectorContext(id: "user-123"))
                }
        }
    }
}

extension EnvironmentValues {
    @Entry var configDirectorClient: ConfigDirectorClient?
}
```

<note>

The SDK follows the app lifecycle so it can release its network connection while the app is backgrounded. See [`connection`](#connection) below to manage that yourself instead.

</note>

### Additional configuration options

These options can be passed in to `ConfigDirectorClientOptions`.

#### `metadata`

The `metadata` option allows you to provide your application's name and version. These values can be used in targeting rules conditionals. For example, if a certain feature should only be enabled starting with a certain version of your application.

Whichever of the two you leave unset is read from the running application's bundle — `CFBundleDisplayName` (falling back to `CFBundleName`) for the name, and `CFBundleShortVersionString` for the version — so most applications do not need to set either one.

```swift [ConfigDirectorSetup.swift]
let client = try ConfigDirectorClient(
    clientSDKKey: "YOUR-CLIENT-SDK-KEY",
    options: ConfigDirectorClientOptions(
        metadata: ConfigDirectorMetaContext(
            appName: "YOUR-APP-NAME",
            appVersion: "1.0.2"
        )
    )
)
```

#### `logger`

By default, the SDK logs to the unified logging system under the `com.configdirector.sdk` subsystem, and it is set to log warnings and errors only. You can configure a `logger` by either creating a ConfigDirector console logger with a different log level, or by conforming to the `ConfigDirectorLogger` protocol to provide your own logger. The protocol can be used to create an adapter to another logging library.

Configure the ConfigDirector console logger to a different level:

```swift [ConfigDirectorSetup.swift]
let client = try ConfigDirectorClient(
    clientSDKKey: "YOUR-CLIENT-SDK-KEY",
    options: ConfigDirectorClientOptions(logger: ConsoleLogger(level: .debug))
)
```

The available levels are `.off`, `.error`, `.warn` (the default), `.info` and `.debug`.

Implement your own logger adapter:

```swift [MyLogger.swift]
import ConfigDirector

struct MyLogger: ConfigDirectorLogger {
    // Messages more verbose than this level are never passed to `log`.
    let level: ConfigDirectorLogLevel = .info

    func log(_ level: ConfigDirectorLogLevel, message: String, error: (any Error)?) {
        // your specific logging library implementation here
    }
}

let client = try ConfigDirectorClient(
    clientSDKKey: "YOUR-CLIENT-SDK-KEY",
    options: ConfigDirectorClientOptions(logger: MyLogger())
)
```

#### `connection`

`ConnectionOptions` accepts six optional values:

- `mode`
  - The connection mode, which can be `.streaming`, `.polling` or `.offline`. It is recommended to use the default of `.streaming` unless you have a specific need to use `.polling` instead. In `.offline` mode the client never connects to ConfigDirector and serves the values you give it; see [Run without a connection](#run-without-a-connection).
  - `.streaming` holds a connection open and receives changes as they happen, reconnecting on its own with a backoff.
  - Defaults to `.streaming`
- `values`
  - The values to serve in `.offline` mode, keyed by config key. It can be given only in `.offline` mode. See [Run without a connection](#run-without-a-connection).
- `pollingInterval`
  - How often to re-fetch config state, in seconds, when `mode` is `.polling`. It has no effect in any other mode. A value below the minimum of 30 seconds is raised to 30 seconds and a warning is logged. See [Polling intervals](https://docs.configdirector.com/getting-started/architecture#polling-intervals).
  - Defaults to `60` seconds
- `timeout`
  - The timeout to be used in initialization and when updating the context. This is how long `initialize` will wait for data from ConfigDirector services before returning. If the timeout is reached, `initialize` will return but the client will still be in an unready status and returning default values. The client will continue to attempt to connect and retrieve config values in the background. It has no effect in `.offline` mode.
  - If your application is used in environments where the users frequently have poor or no connection, you may want to use a lower timeout, or simply don't await the `initialize` call.
  - Defaults to `3` seconds
- `pausesWhileBackgrounded`
  - Whether to pause the connection while the app is in the background and resume it when the app returns to the foreground. Mobile operating systems terminate background connections on their own, so this is enabled by default. Set it to `false` to manage the connection yourself with `pauseNetwork()` and `resumeNetwork()`.
  - It has no effect on macOS, where an app keeps running, and keeps its connections, once it leaves the foreground, and no effect in `.offline` mode.
  - Defaults to `true`
- `baseURL`
  - The base URL used to connect to ConfigDirector services.
  - This should only be provided if your environment requires you to configure a proxy server in order to connect to ConfigDirector services. It has no effect in `.offline` mode.

```swift [ConfigDirectorSetup.swift]
let client = try ConfigDirectorClient(
    clientSDKKey: "YOUR-CLIENT-SDK-KEY",
    options: ConfigDirectorClientOptions(
        connection: ConnectionOptions(mode: .polling, pollingInterval: 600, timeout: 2)
    )
)
```

#### `caching`

`CachingOptions` decides whether the client keeps the last values it received on the device and serves them on the next launch until live values arrive, and where. It is on by default; see [Values kept on the device](#values-kept-on-the-device) for its two fields.

### Events

Events notify you of some key actions from the client. `events` publishes the client's lifecycle changes, and `evaluations` publishes every individual config evaluation. Each is an `AsyncStream` you consume with a `for await` loop, and each access to the property returns an independent stream, so several parts of your app can observe them at once. Canceling the consuming task ends the loop, and every stream is finished when the client is closed.

```swift [ConfigDirectorSetup.swift]
for await event in client.events {
    switch event {
    case let .ready(reason):
        print("Client is ready after \(reason)")
    case let .configsUpdated(update):
        print("Configs updated: \(update.keys), removed: \(update.removedKeys)")
    case let .contextUpdated(context):
        print("Context updated: \(context?.id ?? "none")")
    case .cachedValuesLoaded:
        print("Serving the values kept on the device until live values arrive")
    }
}
```

The following events are published on `client.events`:

- `ready(ConnectReason)`
  - Emitted when the client is initialized, or after reconnection due to a context update or a resumed network connection. When this event is emitted it means the client has received a payload from the ConfigDirector servers and is ready to evaluate configs.
  - The associated `ConnectReason` is the action that triggered the client to connect/reconnect, which can be `.initialization`, `.contextUpdate`, or `.networkResume`.
- `configsUpdated(ConfigsUpdate)`
  - Emitted when a payload is received from the ConfigDirector servers with config data. It is emitted during initialization or context update when an entire config payload is received. After initialization or context update, it is emitted when updates are pushed from the server (or discovered via polling if that connection mode is used).
  - `keys` - A `[String]` listing the config keys that were included in the payload from the server. On a delta update, these are only the configs that changed.
  - `removedKeys` - A `[String]` listing the keys of configs the payload removed. A config is removed when a full payload no longer includes it. Empty when nothing was removed, and always empty on a delta update.
- `contextUpdated(ConfigDirectorContext?)`
  - Emitted whenever the context takes effect, including during initialization. It is emitted before `ready`, therefore should not be relied upon as a lifecycle event but rather as an informational event to track updates to the context.
  - The associated value is the context the client is now evaluating against. It can be `nil`.
- `cachedValuesLoaded`
  - Emitted when the values kept on the device from the last payload are loaded and served, before live values arrive. It is followed by `configsUpdated` listing their keys. See [Values kept on the device](#values-kept-on-the-device). The event carries nothing.

`client.evaluations` publishes a `ConfigEvaluation` every time a config is evaluated, which can be useful for debugging what a screen actually read, and for capturing additional context for analytics events. This includes calls to `value(for:default:)` and evaluations delivered by a `values(for:default:)` stream. A `ConfigEvaluation` carries:

- `key: String` - The config key that was evaluated.
- `value: ConfigEvaluationValue` - The value the config evaluated to. It can be the default value provided to `value(for:default:)` or `values(for:default:)`, for example if the config was evaluated before the client was initialized. Read it back as the type the config was evaluated as with `evaluation.value.as(Bool.self)`, which returns `nil` when the config was evaluated as some other type. Its `description` is a textual form of the value, suitable for logging.
- `valueID: String?` - The value ID, a stable hash of the value that you can send to a third party rather than the `value`. This can be useful for large values, like a JSON config, or to avoid disclosing the values themselves. It is `nil` if the evaluation had to fall back to the in-code default value. To report an experiment to an analytics tool, send the variation instead: the pages for [Amplitude](https://docs.configdirector.com/integrations/analytics/amplitude), [Mixpanel](https://docs.configdirector.com/integrations/analytics/mixpanel), [Google Analytics 4](https://docs.configdirector.com/integrations/analytics/ga4), [Segment](https://docs.configdirector.com/integrations/analytics/segment) and [PostHog](https://docs.configdirector.com/integrations/analytics/posthog) name the event each one reads.
- `variation: Variation?` - The variation that was served, with its `id` and `name`. The `id` stays the same when the variation is renamed, and `name` is `nil` for a variation without one. It is `nil` when the config has no variations or the in-code default value is returned. A value served from the values kept on the device carries it too, unless an earlier version of the SDK kept that value. Versions of the SDK before 1.11.0 do not report it.
- `isDefaultValue: Bool` - Whether or not the evaluation fell back to the default value provided in code.
- `context: ConfigDirectorContext?` - The context the config was evaluated against, if one was set.
- `reason: EvaluationReason` - The reason for the evaluation resolution. In the case the config successfully evaluated based on server-provided targeting rules, it will be `.foundMatch`. A value served from the values kept on the device, before live values arrive, reports `.cached`; see [Values kept on the device](#values-kept-on-the-device). If the evaluation had to fall back to the default value, the `reason` will encode why the fallback was required:

  - `.clientNotReady` - The evaluation happened before the client finished initialization.
  - `.configStateMissing` - The requested config key was not present in the payload received from the server. This could be due to an incorrect config key, or a config that was not enabled to be available to client SDKs.
  - `.valueMissing` - The config had no value for the current context.
  - `.invalidNumber` - The config was requested as a number but the value received from the server could not be converted to a number.
  - `.invalidBoolean` - The config was requested as a boolean but the value received from the server could not be converted to a boolean.
  - `.invalidJSON` - The config was requested as JSON but the value received from the server is not valid JSON.
  - `.typeMismatch` - The config was requested with a data type that did not match the type of the config and no reasonable type conversion was possible, or its JSON does not decode into the type you asked for, for example because a field is missing, `8.5` was read into an `Int`, or an enum value is unknown. Before version 1.11.0 of the SDK, JSON that does not decode reported `.invalidJSON`.

`EvaluationReason` also lists `rolloutSkippedNoIdentifier`. It comes from server SDKs and this SDK never returns it, so a `switch` that lists every reason needs a case for it and nothing more.

`ConfigEvaluation` is `Equatable`, so evaluations can be compared or de-duplicated before they are forwarded on.

```swift [ConfigDirectorSetup.swift]
for await evaluation in client.evaluations where evaluation.isDefaultValue {
    print("'\(evaluation.key)' fell back to its default: \(evaluation.reason.rawValue)")
}
```

```swift [ConfigDirectorSetup.swift]
for await evaluation in client.evaluations {
    guard let isOn = evaluation.value.as(Bool.self) else { continue }

    print("'\(evaluation.key)' evaluated to \(isOn), value ID \(evaluation.valueID ?? "none")")
}
```

<warning>

Do not update view state straight from the `evaluations` stream. The state change re-renders the view, which reads the config again, which publishes another evaluation.

</warning>

### Run without a connection

Set the connection `mode` to `.offline` to run your application without connecting to ConfigDirector, for example in a suite of UI tests where each run pins every flag to a known value. An offline client opens no connection and sends nothing, so the application is invisible to the ConfigDirector dashboard: no evaluations are counted and no config's lifecycle state changes. Every context receives the same value and targeting rules are not applied. An offline client also leaves the device alone: it reads nothing about your app and stores nothing in `UserDefaults`. To test the code that reads your configs rather than run the whole application, use a test client instead; see [Test your code](#test-your-code).

An offline client needs no client SDK key. Create it with `ConfigDirectorClient(options:)`, as below, or pass a blank key, such as an `Info.plist` value left empty in a test build.

Give the values inline, with one value per config key. Your application decides where they come from, for example a dictionary in a test build, or a bundled JSON file it turns into these values:

```swift [ConfigDirectorSetup.swift]
import ConfigDirector

let client = try ConfigDirectorClient(
    options: ConfigDirectorClientOptions(
        connection: ConnectionOptions(
            mode: .offline,
            values: ["new-checkout": true, "max-items": 20, "greeting": "hello", "theme": ["color": "blue"]]
        )
    )
)

await client.initialize()
```

Each value is a `ServedValue`, usually written as a literal, and its config type follows from the case: `true` is a `boolean` config, `20` an `integer` config, `0.15` a `float` config, `"hello"` a `string` config, and `["color": "blue"]` or `["a", "b"]` a `json` config. A string is always a string config, so JSON text meant as a JSON config is given as an object or array literal. A value read with an in-code default value of another type returns the in-code default value with the `typeMismatch` reason, as it does against ConfigDirector.

`initialize` returns once the values are loaded, with the client ready and `ready(.initialization)` published once, followed by `configsUpdated`. A `values(for:default:)` stream created before `initialize` yields the in-code default value and then the offline value once `initialize` loads it; one created after yields the offline value. Neither yields again, since offline values do not change. `updateContext` takes the new context at once and changes no value, and `pauseNetwork()` and `resumeNetwork()` do nothing. `pollingInterval`, `timeout`, `baseURL` and `pausesWhileBackgrounded` have no effect.

With `.offline` and no `values`, the client is ready at once and every config returns its in-code default value with the `configStateMissing` reason.

Creating the client throws when the values cannot be used: `invalidOfflineValue(key:)` for a blank key or a number that is not finite, and `valuesRequireOfflineMode` when `values` is given in `.streaming` or `.polling` mode. A test run with a wrong value fails where the client is created instead of passing on in-code default values.

If you come from LaunchDarkly, a map of values is what LaunchDarkly calls "flags from files", and `.offline` with no values is its "offline mode".

### Values kept on the device

By default, the client 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, shows the values ConfigDirector last sent instead of the in-code default values. Every evaluation served this way reports the reason `.cached`, with `isDefaultValue` set to `false`.

The client is not ready while it serves values kept on the device: `isReady` stays `false`, `isInitializing` stays `true`, `initialize` still waits for live values or its `timeout`, and `ready` is published once live values arrive and replace them. `cachedValuesLoaded` is published when the kept values are loaded, followed by `configsUpdated` listing their keys, and `values(for:default:)` streams yield the kept values.

The values are kept for the context they were evaluated for, and served on the next launch only when the launch context has the same `kind` and `id`. A launch with another context serves the in-code default values until live values arrive, which then replace the kept values. A context without an `id` 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; a context without an `id` keeps its percentage rollout bucket for as long as that instance ID lasts. Name, traits, app name and app version take no part in the match: live values correct them within a second when there is a network. Once the client is running, updating the context 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:

- `enabled`
  - Whether to keep the last values received. With `false`, nothing is read or written, even when a `provider` is given.
  - Defaults to `true`
- `provider`
  - A store of your own, for example an encrypted one, conforming to `CachingProvider`: `read()` returns the stored entry or `nil`, `write(_:)` replaces it, `remove()` deletes it, and `sizeLimit()` returns the largest entry, in bytes, the store accepts. `read`, `write` and `remove` are `async throws`. One provider instance serves one client.
  - Defaults to the app's `UserDefaults`, under a key derived from the client SDK key, with a size limit of 256 KB

```swift [ConfigDirectorSetup.swift]
let client = try ConfigDirectorClient(
    clientSDKKey: "YOUR-CLIENT-SDK-KEY",
    options: ConfigDirectorClientOptions(
        caching: CachingOptions(enabled: true, provider: MyEncryptedStore())
    )
)

await client.initialize()
```

The entry is one string whose format belongs to the SDK and may change between SDK versions; an entry a newer SDK cannot read is removed. Before every write the SDK measures the entry against `sizeLimit()`; above it, the entry is removed and a warning is logged once, so the device never serves values that no longer reflect the set. A provider that fails to read, write or remove is logged once and never stops the client: the worst outcome is the in-code default values. Keeping values on the device is ignored in `.offline` mode, and the test client in `ConfigDirectorTesting` keeps nothing.

If you come from Firebase Remote Config, this is what activated values persisting across restarts gives you; if you come from LaunchDarkly, it is what its mobile SDKs do with the flags they cache on the device.

## Retrieve config values

To synchronously retrieve config values, use the client's `value(for:default:)` method. It requires two arguments. The first argument is the config key, and the second is the default value to be returned if the client has not yet received config values from ConfigDirector services.

You can also subscribe to config value changes via the `values(for:default:)` method. It takes the same two arguments and returns an `AsyncStream` that emits the config's current value on subscription and then every time the evaluated value changes, whether because it was edited in the ConfigDirector dashboard or because the context was updated. Consecutive identical values are not re-emitted. When a full payload no longer includes the watched config, the stream emits the default value, as `value(for:default:)` would now return it. Canceling the task consuming the stream stops watching.

```swift [ContentView.swift]
// Retrieve the current value. The default value decides the type the config
// is read as, and is returned until the client is ready.
let darkMode = client.value(for: "my-config-key", default: false)

// Subscribe to value updates. The stream yields the current value right away
// and then every time the evaluated value changes.
for await darkMode in client.values(for: "my-config-key", default: false) {
    print("Value updated: \(darkMode)")
}
```

Both methods infer their type from the default value. `Bool`, `String`, `Int` and `Double` are supported out of the box. If there is a type mismatch at runtime, the SDK will attempt to convert the served value to the requested type. If the conversion fails, it will return the default value rather than trapping. Mismatched types at runtime are captured by the telemetry collector and will surface as warnings in the ConfigDirector dashboard.

```swift [ContentView.swift]
client.value(for: "my-string-config-key", default: "Default")

client.value(for: "my-integer-config-key", default: 100)

client.value(for: "my-boolean-config-key", default: false)
```

### JSON configs

A config holding a JSON document is read with `value(for:as:default:)`, which decodes it into any `Decodable` type. It returns the default value when the config is not a JSON config, or when its document cannot be decoded into the type you asked for:

```swift [ContentView.swift]
struct Theme: Decodable, Equatable {
    let primary: String
    let cornerRadius: Double

    static let fallback = Theme(primary: "#101010", cornerRadius: 8)
}

let theme = client.value(for: "theme", as: Theme.self, default: .fallback)
```

`values(for:as:default:)` is the streaming counterpart. Its type has to be `Equatable` as well, since that is how the stream knows a decoded value did not change:

```swift [ContentView.swift]
for await theme in client.values(for: "theme", as: Theme.self, default: .fallback) {
    self.theme = theme
}
```

### Custom value types

To read a config as one of your own types, conform it to `ConfigValue`. A config value arrives as the string the server served, and `configValueKind` decides which configs the type can be read from — `.boolean`, `.string`, or `.number`. Returning `nil` from the initializer evaluates the config to the caller's default value:

```swift [Locale+ConfigValue.swift]
import ConfigDirector

extension Locale: ConfigValue {
    public static var configValueKind: ConfigValueKind { .string }

    public init?(configValue: String) {
        self.init(identifier: configValue)
    }
}

let locale = client.value(for: "default-locale", default: Locale(identifier: "en_US"))
```

### Reading configs in SwiftUI

`value(for:default:)` is synchronous and makes no network calls, so it is 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, drive a `@State` from `values(for:default:)` inside a `.task`. The stream yields the current value immediately, so there is no frame where the view shows something other than the default before the first value arrives:

```swift [DarkModeToggle.swift]
import ConfigDirector
import SwiftUI

struct DarkModeToggle: View {
    let client: ConfigDirectorClient

    @State private var isOn = false

    var body: some View {
        Toggle("Dark mode", isOn: $isOn)
            .task {
                for await value in client.values(for: "dark-mode", default: false) {
                    isOn = value
                }
            }
    }
}
```

<note>

`.task` cancels its work when the view disappears and starts it again when the view returns, which ends and re-subscribes the stream for you. Use `.task(id:)` when the config key or the default value can change, so the stream is replaced when they do.

</note>

## Update the context

A context can be provided when initializing the client:

```swift [ConfigDirectorSetup.swift]
import ConfigDirector

let client = try ConfigDirectorClient(clientSDKKey: "YOUR-CLIENT-SDK-KEY")

await client.initialize(
    context: ConfigDirectorContext(
        id: "12345",
        name: "Example User",
        traits: [
            // Any arbitrary traits which can be referenced in targeting rules
            "region": "North America",
        ]
    )
)
```

The context can also be updated via `updateContext`:

```swift [ContentView.swift]
await client.updateContext(
    ConfigDirectorContext(
        id: "654321",
        name: "Another User",
        traits: ["region": "Australia"]
    )
)

// Update it to an anonymous context when a user signs out. Leaving `id` unset
// makes ConfigDirector derive an identifier that lasts until the app is uninstalled.
await client.updateContext(ConfigDirectorContext(isAnonymous: true))
```

To evaluate configs for an entity other than a user, such as a tenant, set the context kind with `kind`:

```swift [ContentView.swift]
await client.updateContext(
    ConfigDirectorContext(
        id: "acme",
        kind: "tenant",
        name: "Acme Inc.",
        traits: ["plan": "enterprise"]
    )
)
```

Leaving `kind` out means `user`. 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 configs are evaluated as if no context had been given. Context kinds are available from version 1.8.0 of the SDK.

<note>

In client SDKs (browser and mobile), updating the context re-establishes a new connection to ConfigDirector servers with the new context. While the new connection is in flight, config values will continue to evaluate to the values currently held in memory from the prior context.<br />


Awaiting `updateContext` will wait until the new config values are downloaded or the connection times out. In the case of a timeout, the client will continue to attempt to connect with the new context in the background.

</note>

Traits are written as ordinary Swift literals. Strings, integers, doubles, booleans, arrays, dictionaries and `nil` are all accepted:

```swift [ContentView.swift]
await client.updateContext(
    ConfigDirectorContext(
        id: "user-123",
        name: "Ada Lovelace",
        traits: [
            "plan": "pro",
            "seats": 12,
            "beta": true,
            "regions": ["us-east", "eu-west"],
        ]
    )
)
```

For a signed-out user, set `isAnonymous` to `true`. The values are still used to evaluate targeting rules, but the context is not persisted and does not appear in the dashboard.

The SDK keeps an instance ID in the app's `UserDefaults` until the app is uninstalled, and ConfigDirector derives the identifier of a context without an `id` from it. A person who uses the app without signing in keeps that identifier, and their percentage rollout bucket, from one app start to the next, and counts as one [monthly active user](https://docs.configdirector.com/getting-started/pricing-and-billing#billing-metrics) however often they open the app.

## Track events

`track` reports to ConfigDirector that something happened in your application, such as a completed checkout. ConfigDirector shows tracked events on the Live feed and counts them for each variation of a running experiment; see [Tracked events](https://docs.configdirector.com/monitoring/activity#tracked-events).

`track` accepts the name of the event and optional `TrackOptions` with a `value` and `details`, and reports the event for the client's current context:

```swift [Checkout.swift]
client.track(
    "checkout-completed",
    options: TrackOptions(value: 49.9, details: ["plan": "pro", "seats": 3])
)

client.track("tutorial-skipped")
```

- `value` is a number the event measures, such as an amount of money, a count or a duration. A literal is enough for a fixed number, and a variable names its case: `.int`, `.double` or `.decimal`, as in `TrackOptions(value: .decimal(order.total))`. A `Decimal` is sent with every digit it holds, which makes it the choice for an amount of money.
- `details` is a dictionary describing the event, usually written as literals. Its values are strings, numbers, booleans, `nil`, or nested dictionaries and arrays. A date, written `.date(subscription.startDate)`, is sent as ISO 8601 text in UTC, and a number that is not finite as `null`.

An event counts for an experiment only when the current context has an `id`, the same one the experiment's config was evaluated for. Before the client has a context, or for a context without an `id`, the event is still reported and counts for no experiment. For a context marked `isAnonymous`, the event is reported without the `id`, so it counts for no experiment either.

`track` returns nothing and never throws. The event is sent with the SDK's next telemetry report, every 30 seconds and when the app goes to the background. In [offline mode](#run-without-a-connection), `track` does nothing. The SDK applies these limits, and logs one warning for each of them per telemetry report:

<table>
<thead>
  <tr>
    <th>
      Limit
    </th>
    
    <th>
      Beyond it
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      An event name of 1 to 150 characters
    </td>
    
    <td>
      The event is not reported.
    </td>
  </tr>
  
  <tr>
    <td>
      1,000 tracked events in one telemetry report
    </td>
    
    <td>
      Further events are not reported until that report is sent.
    </td>
  </tr>
  
  <tr>
    <td>
      Details of up to 20 top-level keys and 1 KB as JSON
    </td>
    
    <td>
      The details are left out and the event is still reported.
    </td>
  </tr>
  
  <tr>
    <td>
      A <code>
        value
      </code>
      
       that is a finite number
    </td>
    
    <td>
      The value is left out and the event is still reported.
    </td>
  </tr>
</tbody>
</table>

ConfigDirector applies limits of its own to the events it stores; see [Limits](https://docs.configdirector.com/monitoring/activity#limits).

From version 1.11.0 of the SDK, 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.

`track` is available from version 1.11.0 of the SDK, which adds the `TrackOptions`, `TrackedEventValue`, `TrackedEventDetails` and `TrackedEventDetailValue` types.

## Other useful client features

The client provides additional properties and methods.

### `evaluate`

Evaluates a config the way `value(for:default:)` does and returns the `ConfigEvaluation` behind it along with the value. It is the same evaluation `evaluations` publishes, with whether the value is the default, the `reason`, the `valueID` and the `variation`, so use it where the reason or the variation matters at the point of the read:

```swift [ContentView.swift]
let (darkMode, evaluation) = client.evaluate("dark-mode", default: false)
if evaluation.reason == .clientNotReady {
    // The client has no values yet, so darkMode is the in-code default value.
}
```

`evaluate(_:as:default:)` does the same for a JSON config. The `variation` on an evaluation is available from version 1.11.0 of the SDK, which adds the `Variation` type.

### `context`

Returns the current context (which may be `nil`). When calling `updateContext`, the `context` is not immediately updated. The `context` is updated after the new connection for the new context succeeds (or times out and goes on retry).

### `isReady`

Returns a `Bool` indicating if the client has been successfully initialized and is ready to evaluate configs for the given context. It is initially `false` and becomes `true` after `initialize` succeeds.
Upon calling `updateContext` it becomes `false` again and it is set to `true` once `updateContext` succeeds. It stays `false` while the client serves the [values kept on the device](#values-kept-on-the-device).

### `isInitializing`

Returns a `Bool` indicating whether the client is trying to get its very first config state from the server. It is `false` on creation, becomes `true` when `initialize` is called on a client that has never received config state, stays `true` through timeouts and retries, and becomes `false` when the first config state arrives, when an unrecoverable connection error stops the retries, or on `close()`. `updateContext` and `resumeNetwork` never set it, and it stays `true` while the client serves the [values kept on the device](#values-kept-on-the-device).

To show a loading state on a slow connection rather than switching from the in-code default value to the evaluated value, end it when `initialize` returns: it returns once the values arrive, and at the latest once the `timeout` elapses. Don't end it when `isInitializing` turns `false`, because that can happen long after the timeout, for example when the app starts without a network.

### `pauseNetwork()` and `resumeNetwork()`

`pauseNetwork()` releases the network connection without discarding config state, event streams, or watch streams, and `resumeNetwork()` re-establishes it using the last context given to `initialize` or `updateContext`.

The client already does this on its own while the app is backgrounded, so these are only needed if you set `pausesWhileBackgrounded` to `false` in order to manage the connection yourself.

### `close()`

Closes the connection, every watch stream, and every event stream, and reports whatever telemetry is left. The client cannot be used afterwards.

The client closes itself when it is released, so calling `close()` is only necessary to shut it down while a reference to it is still held.

## Test your code

Use the SDK's testing library, the `ConfigDirectorTesting` product of the same package, to test the code that reads your configs and flags. It creates a **test client**: the SDK's real client connected to an in-memory server that your test controls. Only the connection to ConfigDirector, the telemetry, and the app lifecycle observer are replaced. Everything else is the same code that runs in production, so the code under test behaves exactly as it does against ConfigDirector, and no network connection is opened, no telemetry is sent, and no values are kept on the device. The product ships in the package you already depend on, so there is nothing else to add; link it into your test target only.

```swift [Package.swift]
.testTarget(
    name: "YourAppTests",
    dependencies: [
        "YourApp",
        .product(name: "ConfigDirectorTesting", package: "configdirector-swift-sdk"),
    ]
),
```

In an Xcode project, add the `ConfigDirectorTesting` library to your test target under **Frameworks and Libraries**; the package itself is already added for the app.

```swift [CheckoutTests.swift]
import ConfigDirectorTesting
import Testing

struct CheckoutTests {
    @Test func enablesTheNewCheckoutWhenTheFlagIsOn() async {
        let testClient = makeTestClient(values: ["new-checkout": true, "max-items": 20])
        defer { testClient.client.close() }
        await testClient.client.initialize()

        let checkout = Checkout(client: testClient.client)
        #expect(checkout.isNewCheckoutEnabled)

        testClient.setValue(false, for: "new-checkout")
        #expect(!checkout.isNewCheckoutEnabled)
    }
}
```

`testClient.client` is a `ConfigDirectorClient`, so it goes anywhere your code accepts one. It starts uninitialized, like a production client, because the code under test usually owns the call to `initialize`; with nothing held or failed, `initialize` completes at once with the client ready. Close it when the test is done, as your production code would.

### Watching values

`values(for:default:)` streams work as they do in production: a stream yields the current value when it is created and then every time the evaluated value changes, so a test reads the next element after each change. A SwiftUI view driven by such a stream, as in [Reading configs in SwiftUI](#reading-configs-in-swiftui), follows the test client the same way.

```swift [GreetingTests.swift]
let testClient = makeTestClient(values: ["greeting": "hello"])
defer { testClient.client.close() }
var greetings = testClient.client.values(for: "greeting", default: "none").makeAsyncIterator()
#expect(await greetings.next() == "none")

await testClient.client.initialize()
#expect(await greetings.next() == "hello")

testClient.setValue("hi", for: "greeting")
#expect(await greetings.next() == "hi")
```

A stream keeps only the newest value, so two `setValue` calls before the next read arrive as one element, and `events` keeps the newest 256 events.

### Values

`values`, `setValue`, and `replaceValues` take `TestValue`s, usually written as literals, and the config type follows from the case: `true` is a boolean config, `20` an integer config, `2.5` a float config, `"Ada"` a string config, `["theme": "dark", "limit": 3]` a JSON object, and `["x", "y"]` a JSON array. A string is always a string config, so JSON text meant as a JSON config is given as an object or array literal. Every value is served to every context; a test that needs different values per context is written as one test per value. There is no null value; `removeValue(for:)` removes one. A blank key or a number that is not finite is a programming error and stops the test with a precondition failure.

Reads behave as they do in production: `setValue(true, for: "k")` read as a `String` returns the in-code default value and publishes a `typeMismatch` evaluation, `setValue(2.5, for: "k")` read as an `Int` returns `2`, and `setValue("", for: "k")` serves the in-code default value with the `valueMissing` reason. A JSON object is encoded with its keys in sorted order, and `value(for:as:default:)` decodes it into your `Decodable` type.

### Controls

<table>
<thead>
  <tr>
    <th>
      Control
    </th>
    
    <th>
      Effect
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        setValue(_:for:)
      </code>
    </td>
    
    <td>
      Stores the value and, once the client is connected, delivers an update carrying only that key. Reads see it when <code>
        setValue
      </code>
      
       returns; <code>
        values(for:)
      </code>
      
       streams of the key and <code>
        events
      </code>
      
       yield it.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        removeValue(for:)
      </code>
    </td>
    
    <td>
      Removes the value and delivers a full update without it. Reads return the in-code default value with the <code>
        configStateMissing
      </code>
      
       reason, <code>
        values(for:)
      </code>
      
       streams of the key yield the default, and <code>
        configsUpdated
      </code>
      
       lists the key in <code>
        removedKeys
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        replaceValues(_:)
      </code>
    </td>
    
    <td>
      Replaces every stored value, disarms any armed hold or failure, and delivers a full update. Use it to reset a test client shared across tests.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        holdInitialization()
      </code>
    </td>
    
    <td>
      The next <code>
        initialize
      </code>
      
       waits until <code>
        completeInitialization()
      </code>
      
       or <code>
        failInitialization()
      </code>
      
      , or until the client's <code>
        timeout
      </code>
      
       elapses.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        completeInitialization()
      </code>
    </td>
    
    <td>
      Delivers the stored values to the held <code>
        initialize
      </code>
      
      , so the client is ready when it returns, and lets <code>
        initialize
      </code>
      
       complete. Called while a hold is armed but not picked up, it disarms the hold.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        failInitialization()
      </code>
    </td>
    
    <td>
      Fails the held <code>
        initialize
      </code>
      
       the way an invalid SDK key does: it completes promptly, the client is not ready, and an error is logged. Called with no <code>
        initialize
      </code>
      
       held, it arms the next one to fail.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        holdContextUpdate()
      </code>
      
      , <code>
        completeContextUpdate()
      </code>
      
      , <code>
        failContextUpdate()
      </code>
    </td>
    
    <td>
      The same for the next <code>
        updateContext
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        contextUpdates
      </code>
    </td>
    
    <td>
      The context of every <code>
        initialize
      </code>
      
       and <code>
        updateContext
      </code>
      
       call, in order. <code>
        initialize
      </code>
      
       without a context records an empty context, and <code>
        resumeNetwork
      </code>
      
       is not recorded.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        trackedEvents
      </code>
    </td>
    
    <td>
      The events the code under test tracked with <code>
        track
      </code>
      
      , in call order, each as a <code>
        TrackedEvent
      </code>
      
       with its <code>
        name
      </code>
      
      , <code>
        context
      </code>
      
      , <code>
        value
      </code>
      
       and <code>
        details
      </code>
      
      , which compare by value. An event whose name the SDK would not report is not recorded, a value or details the SDK would leave out are missing from the record, and details hold what the SDK sends, so a date is its ISO 8601 text. The limit of 1,000 events per telemetry report does not apply to the record. Reading it gives a copy, so read it again after the code under test tracks more. <code>
        replaceValues
      </code>
      
       leaves it alone, so a test client shared across tests clears it with <code>
        testClient.trackedEvents.removeAll()
      </code>
      
      .
    </td>
  </tr>
</tbody>
</table>

The initialization controls act only on `initialize` and the context update controls only on `updateContext`; `resumeNetwork` is never held or failed. After a failed attempt, the next attempt succeeds and delivers the values stored in the meantime. A held `initialize` suspends its caller, so start it in a `Task` and drive it from the test:

```swift [LoadingTests.swift]
let testClient = makeTestClient(values: ["new-checkout": true], timeout: 0.5)
defer { testClient.client.close() }
testClient.holdInitialization()

let initialization = Task { await testClient.client.initialize() }
try await Task.sleep(nanoseconds: 50_000_000)
#expect(testClient.client.isReady == false)
#expect(testClient.client.isInitializing)

testClient.completeInitialization()
await initialization.value
#expect(testClient.client.isReady)
```

### Options

`makeTestClient` takes `values`, `timeout` (the client's connection timeout, which bounds how long a held attempt waits; defaults to the SDK's production timeout of 3 seconds), and `logger` (defaults to the SDK's `ConsoleLogger`, which writes to the unified logging system; pass a `ConfigDirectorLogger` of your own to capture what the client logs). Since the test client sends no telemetry, a warning is logged every time a tracked event or part of one is left out, not once per telemetry report.

### What to expect

- Under the test client, `initialize` publishes `contextUpdated`, then `ready`, then `configsUpdated`, all before it returns.
- A held attempt that times out, or that is interrupted by `pauseNetwork` or `close`, leaves the client not ready until the next attempt, applies the context it was given, and logs the SDK's timeout warning, which says the client will keep retrying, as production streaming would. A held `initialize` ended by `close` logs it too, and `isInitializing` stays `true` after a timeout, as it does in production until the first config state arrives.
- The client runs `initialize`, `updateContext`, and `resumeNetwork` one at a time, so an attempt started while another is held waits for it to be completed, failed, or ended.
- `values(for:)` streams yield on creation and then only when the evaluated value changes, as in production, so a `setValue` to the value already served yields nothing, while `events` still carries the `configsUpdated`.
- `pausesWhileBackgrounded` has no effect: the test client does not observe the app lifecycle. Call `pauseNetwork` and `resumeNetwork` to test that path; values set while paused are delivered on resume.
- After `close`, the test client's controls are silent no-ops, every stream finishes, and no task from the SDK is left running.


## Sitemap

See the full [sitemap](https://docs.configdirector.com/sitemap.md) for all pages.
