Skip to content
FlagSwiftDocs

Swift SDK

iOS, macOS, tvOS and watchOS, with a SwiftUI layer.

Compare SDKs

Use this SDK in apps for Apple platforms. It takes a client key, so your server decides and only outcomes reach the device. Targeting lists and rollout numbers stay private, and flags are cached on the device so the app has them at launch even when offline. For other mobile platforms see the Flutter and React Native SDKs. Options and behaviour every SDK shares are on Options and behaviour.

Not yet compiled

This package has not been compiled or run, and the SwiftUI layer has no tests. Run swift build and swift test on a Mac first, and check the SwiftUI views in an Xcode project. The package URL is also a placeholder until the publishing location is decided, so install from the repository for now.

At a glance#

Install
Swift Package: FlagSwift
Requires
Swift 5.9, iOS 14+
Key
Client key (fs_client_)
Evaluates
On the server, for one person
Real-time updates
No, it polls
Works offline from
UserDefaults
Outcome analytics
Yes
Verified
Not yet compiled

Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.

Installation#

swift
.package(url: "https://github.com/<your-org>/flagswift-swift.git", from: "2.0.0")

It needs Swift 5.9 and iOS 14, macOS 11, tvOS 14 or watchOS 7 or newer. Add the FlagSwift library product to your target, then import FlagSwift.

Initialization#

You need a client key (fs_client_…) from the API Keys page, which is meant to ship in apps, and the address of your FlagSwift server. Never ship a server key (fs_srv_…) in an app. Create the client once and start it.

App.swift
import FlagSwift

let client = FlagSwiftClient(
    apiKey: "fs_client_...",
    baseURL: URL(string: "https://flags.example.com")!,   // your FlagSwift server (required)
    user: FlagSwiftUser(identifiers: ["user-123"]),
    fallbacks: ["new-checkout": .bool(false)]
)

await client.start()   // loads the cache, fetches, starts polling; never throws

Startup never blocks for long

start() waits at most initTimeout (5 seconds) for the fetch. The fetch carries on in the background and applies when it completes. The cache read itself is synchronous.

Connection options#

The key and base URL are required. The convenience initializer throws a FlagSwiftError with MISSING_API_KEY or MISSING_BASE_URL for setup mistakes. Everything else lives on FlagSwiftClient.Configuration and has a default.

Common properties of FlagSwiftClient.Configuration
PropertyTypeDescription
apiKey, baseURL*String, URLA client key and your server address.
environmentString?Only for project-wide keys.
refreshIntervalTimeIntervalSeconds between checks for changes. Default 30. Zero turns polling off.
fallbacks[String: JSONValue]Served for unknown flags and before anything loads.
initialFlags[String: ClientFlag]?Start ready with these flags, so the first screen is already correct.
storageFlagStorage?Default UserDefaultsStorage(). nil turns the cache off.
initTimeout, timeoutTimeIntervalThe longest start() waits, and per request. Default 5 seconds each.
maxRetriesIntDefault 2.
manageLifecycleBoolDefault true. Pauses in the background and refreshes on return.
autoExposuresBoolReport an exposure whenever a flag is read. Default false.

Check flags#

isEnabled is synchronous, so it is safe in UI code. It returns the flag, then your fallback, then the configured one, then false. The client never crashes on an unknown flag or a failed fetch.

swift
if client.isEnabled("new-checkout") {
    showNewCheckout()
}

// Your own default when the flag is not found.
let beta = client.isEnabled("beta-banner", fallback: true)

Check variants and values#

A flag can serve a named variant, such as a theme or a plan limit. variant gives its key, and value gives what it carries, decoded into your own type if you ask.

swift
let variant = client.variant("theme")                     // "dark", "light" or nil
let raw = client.value("theme")                           // a JSONValue?
let theme = client.value("theme", as: Theme.self, fallback: .light)  // decoded into your type

let flag = client.flag("theme")                           // enabled, variant, value and version

SwiftUI#

Attach the client to the view tree with the .flagSwift modifier. It starts the client when the view appears, and views re-render when flags change.

swift
@main struct MyApp: App {
    let client = FlagSwiftClient(apiKey: "fs_client_...", baseURL: URL(string: "https://flags.example.com")!)

    var body: some Scene {
        WindowGroup { ContentView().flagSwift(client) }
    }
}

struct ContentView: View {
    @Flag("new-checkout") var newCheckout

    var body: some View {
        Feature("promo-banner") { PromoBanner() } otherwise: { EmptyView() }
        if newCheckout { NewCheckout() } else { OldCheckout() }
    }
}

@Flag is a property wrapper whose value is the flag. Feature shows its content when the flag is on and the optional otherwise view when it is off. FlagStore is an ObservableObject over the client for code that needs isEnabled, variant or value with a published version.

Change the person#

Call identify after a login, logout or tenant switch. It switches the person and refreshes every flag.

swift
await client.identify(FlagSwiftUser(identifiers: ["user-456"]))

A FlagSwiftUser carries identifiers, accounts, devices and attributes. Percentage rollouts bucket on the first identifier. Offline, identify loads that person's cached flags if there are any. Otherwise the previous person's last good flags stay in place until the refresh succeeds, so they may briefly be the previous person's outcomes.

Updates#

The Swift SDK polls and has no real-time stream. It checks every refreshInterval (30 seconds). On iOS, tvOS and macOS it pauses polling in the background and refreshes at once when the app returns to the foreground. Turn that off with Configuration.manageLifecycle = false and call pause() and resume() yourself. Outside SwiftUI, subscribe calls your handler with a FlagState on every change.

swift
let subscription = client.subscribe { state in
    print("flags from", state.source, "status", state.status)
}
// later
subscription.cancel()

Offline and errors#

Once the client has flags, from a fetch, the offline cache or initialFlags, evaluation is purely local and never throws. It keeps working with no internet and through a FlagSwift outage.

What happens when something goes wrong
SituationDescription
A refresh failsThe last good flags stay. The state becomes error, onError is called, and polling backs off up to about six minutes. The next success resets it.
First load, nothing cachedYou get your fallbacks, then false, until the response arrives.
Next launch, offlineThe flags saved in UserDefaults apply at once. A corrupt entry is ignored, and a cache never overwrites network or initial flags.
App in the backgroundPolling pauses, and returning to the foreground refreshes at once and resets the failure count.
Reading the stateclient.state has status, flags, error, lastUpdated and source (none, bootstrap, cache or network).

Outcome analytics#

Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or set autoExposures, which also makes the SwiftUI helpers report. Only the person's identifier, the flag, the variant and the event name leave the device.

swift
client.trackExposure("checkout")            // this user was shown the flag's current outcome
client.track("purchase", value: 49.0)       // what they did; the value is optional
await client.flushAnalytics()               // send what is queued now
let status = client.analyticsStatus         // pending, sent, dropped, enabled

See Outcomes for how results are read in the console.

Reference#

Swift Package FlagSwift, Swift 5.9, iOS 14, macOS 11, tvOS 14 and watchOS 7 or newer. The client is thread-safe and uses a lock and callbacks rather than an actor, so isEnabled stays synchronous for UI code.

FlagSwiftClient.Configuration
PropertyTypeDescription
apiKey, baseURL*String, URLA client key and your server address. Created with Configuration(apiKey:baseURL:).
environmentString?Only for project-wide keys.
refreshIntervalTimeIntervalSeconds. Default 30.
initTimeoutTimeIntervalSeconds. Default 5.
timeoutTimeIntervalPer request. Default 5.
maxRetriesIntDefault 2.
fallbacks[String: JSONValue]Served for unknown flags or before anything loads.
initialFlags[String: ClientFlag]?Start ready with these flags.
storageFlagStorage?Default UserDefaultsStorage(). nil turns the cache off.
reportErrorsBoolDefault true.
manageLifecycleBoolDefault true. Pauses in the background and refreshes on return.
sdkNameStringDefault ios.
FlagSwiftClient members
MemberDescription
init(configuration:user:transport:onError:sleep:random:)Designated initializer. onError receives a FlagSwiftError; transport is a FlagHTTPTransport (URLSessionTransport by default).
convenience init(apiKey:baseURL:environment:user:refreshInterval:initTimeout:fallbacks:initialFlags:storage:transport:...)Throws a FlagSwiftError with MISSING_API_KEY or MISSING_BASE_URL for setup mistakes.
static func validate(apiKey:baseURL:) -> FlagSwiftError?Checks the two required values without creating a client.
func start() asyncLoads the cache, fetches and starts polling. Waits up to initTimeout for the fetch, but the cache read is not bounded by it.
func identify(_ user: FlagSwiftUser?) asyncSwitches the person and refreshes.
func refresh() asyncFetch now. A failure keeps the last flags.
func trackExposure(_ key: String) / func track(_ event: String, value: Double?)Report that this user was shown the flag's current outcome, and what they then did. Never throw. track sends the user's pending exposures first.
func flushAnalytics() / var analyticsStatusSends what is queued now (best effort). analyticsStatus has pending, sent, dropped and enabled (nil while unknown). Configuration.autoExposures queues an exposure on every read (default false).
func pause() / resume() / stop()Stop and restart polling; stop is final.
var state: FlagStatestatus, flags, error, lastUpdated and source.
func isEnabled(_ key: String, fallback: Bool? = nil) -> BoolSynchronous. The flag, then your fallback, then the configured one, then false.
func variant(_ key: String) -> String?The served variant.
func flag(_ key: String) -> ClientFlag?The raw result: enabled, variant, value and version.
func value(_ key: String) -> JSONValue?The variant's value as JSON.
func value<T: Decodable>(_ key: String, as: T.Type, fallback: T?) -> T?The value decoded into your own type.
func subscribe(_ handler: (FlagState) -> Void) -> FlagSubscriptionCalled on every change. Cancel through the returned subscription.
Swift types and views
NameDescription
FlagSwiftUseridentifiers, accounts, devices and attributes ([String: JSONValue]). FlagSwiftUser.anonymous has none.
FlagState, FlagStatus, FlagSourceStatus is idle, loading, ready or error. Source is none, bootstrap, cache or network.
FlagStorage, UserDefaultsStorage, MemoryStorageFlagStorage has read(_:) and write(_:_:). UserDefaultsStorage is the default; MemoryStorage is for tests.
FlagSwiftErrormessage, code, status and retryable.
JSONValueA JSON value type for flag values and attributes.
FlagStoreAn ObservableObject over the client. Publishes version; offers isEnabled, variant, value and state.
.flagSwift(client, autoStart: true)A view modifier that provides the client to the view tree and starts it.
Feature("flag") { ... } otherwise: { ... }Shows the content when the flag is on; the optional otherwise view when it is off.
@Flag("flag", fallback: nil)A property wrapper whose value is the flag, refreshing the view on change.
pollDelay(...)The retry and polling delay helper.

Not yet compiled

The Flutter and Swift SDKs have never been compiled or run, and the Swift UI layer has no tests. Run flutter analyze && flutter test and swift test before relying on them.