The ABsmartly SDK for iOS, macOS, tvOS, watchOS, visionOS and Linux: async/await, Swift 6 strict
concurrency (every public type is Sendable) and no third-party dependencies linked on Apple
platforms (swift-crypto is linked on Linux only).
Using 1.x? This is 2.x. The 1.x line (module
ABSmartly, PromiseKit API) is maintained on therelease/1.xbranch, with bug fixes for 12 months after 2.0.0 (see SUPPORT.md). To move to 2.x, follow MIGRATING.md.
| Platform | Minimum |
|---|---|
| iOS / iPadOS | 15.0 |
| macOS | 12.0 |
| Mac Catalyst | 15.0 |
| tvOS | 15.0 |
| watchOS | 8.0 |
| visionOS | 1.0 |
| Linux | Swift 6.0 |
Building needs Swift 6.0 or later (Xcode 16 or later).
dependencies: [
.package(url: "https://github.com/absmartly/swift-sdk.git", from: "2.1.0")
],
targets: [
.target(name: "App", dependencies: [
.product(name: "ABsmartly", package: "swift-sdk"),
// Optional: SwiftUI property wrappers
.product(name: "ABsmartlyUI", package: "swift-sdk"),
])
]In Xcode: File → Add Package Dependencies…, enter https://github.com/absmartly/swift-sdk.git
and choose the ABsmartly (and optionally ABsmartlyUI) product.
2.1.0 is Swift Package Manager only. It is not published to CocoaPods; use the SwiftPM installation above for holdouts and the 2.x API.
The last available CocoaPods release is ABSmartlySwiftSDK 1.3.4 (legacy 1.x API and module
ABSmartly), not ABsmartly 2.0.0 or 2.1.0. It does not include holdouts or the Swift 6 API:
pod 'ABSmartlySwiftSDK', '1.3.4' # legacy SDK, not Swift 2.xThe CocoaPods trunk stops accepting new versions on 2026-12-02. The explicit 2.1.0 SwiftPM-only exception applies regardless of that date.
import ABsmartly
let client = try ABsmartlyClient(
endpoint: URL(string: "https://your-company.absmartly.io/v1")!,
apiKey: apiKey,
application: "website",
environment: .production
)Create one client and keep it for the lifetime of the app. It is Sendable, so you can share it
between tasks and actors.
var configuration = ABsmartlyClient.Configuration(
endpoint: URL(string: "https://your-company.absmartly.io/v1")!,
apiKey: apiKey,
application: "website",
environment: "staging")
configuration.applicationVersion = "1042"
configuration.timeout = 3
configuration.retries = 3
configuration.transport = transport
configuration.eventLogger = .custom { context, event in
print("ABsmartly event: \(event)")
}
let client = try ABsmartlyClient(configuration: configuration)transport is any type conforming to Transport (one async method that sends an HTTPRequest).
Use it to route requests through your own networking stack; the SDK still builds the requests,
retries and decodes the responses.
There are three ways to create a context:
// 1. Await until ready (common case); throws if the context data can't be fetched
let context = try await client.context(units: [.deviceID: deviceID])
// 2. Create now, wait later (e.g. start at launch, await before the first screen needs it)
let context = client.makeContext(units: [.deviceID: deviceID])
try await context.ready()
// 3. Pre-fetched data from your server: synchronous, ready immediately
let context = client.context(units: [.deviceID: deviceID], data: contextData)contextData is a ContextData (it is Codable): fetch it on your server, or with
try await client.fetchContextData().
All three take the same optional arguments:
let context = try await client.context(
units: [.deviceID: deviceID, .userID: "user-42"],
attributes: ["plan": "pro", "age": 42],
overrides: ["exp_banner": 1],
options: Context.Options(publishDelay: 0.1, refreshInterval: 300)
)Unit types are UnitType values: .deviceID, .userID, .sessionID, or any string literal
("email").
- Reads stay synchronous:
treatment(for:),variable(_:default:),track(_:properties:)and the other reads neverawait, so you can call them from a SwiftUIbody, a table view cell or any thread. - Network calls are
async:ready(),refresh(),publish()andclose(). ContextisSendable: store it in a@MainActorview model or pass it into aTaskwithout warnings in Swift 6.
@MainActor
final class CheckoutModel: ObservableObject {
@Published var showExpressCheckout = false
private let context: Context
init(context: Context) {
self.context = context
showExpressCheckout = context.treatment(for: "exp_checkout") == 2
}
func purchase(total: Double) {
context.track("purchase", properties: ["total": .double(total)])
Task { try? await context.publish() }
}
}switch context.state {
case .loading: print("loading")
case .ready: print("ready")
case .failed(let error): print("failed: \(error)")
case .closing, .closed: print("closed")
}A context whose data could not be fetched is .failed: its reads return the control variant and
the defaults, and it publishes nothing.
let variant = context.treatment(for: "exp_checkout")
if variant == 1 {
// show the new checkout
}The first read of an experiment queues an exposure, which is published automatically. To read without exposing ("peek"):
let peeked = context.treatment(for: "exp_checkout", exposing: false)Helpers:
if context.isInTreatment("exp_checkout") {
// variant != 0
}
let style = context.treatment(for: "exp_checkout", as: CheckoutVariant.self) // enum CheckoutVariant: Intlet color: String = context.variable("button.color", default: "blue")
let limit = context.variable("cart.limit", default: 10)
let config: CheckoutConfig = context.variable("checkout", default: .standard) // any Decodable
let raw: JSONValue? = context.variableValue("checkout")Reading a variable exposes the experiment that provides it. Pass exposing: false to peek.
When several experiments define the same variable key, they are checked in ascending experiment id order and the first one this context is in (assigned, overridden or set by an assignment rule) wins. Only that experiment is exposed. If its variant does not define the key, the read returns the default; a later experiment's value is never used. If the context is in none of them but is held out of one (see Holdouts), the first held-out experiment's control value is returned, or the default when its control does not define the key. As in the Java SDK, an assignment already resolved in the context keeps its variant's variables until the experiment's iteration (or another assignment input) changes, so a refresh that changes only variant configs does not replace them.
Overrides force a variant, for example in QA builds. Set them at creation, one at a time, or several at once:
let context = client.context(
units: [.deviceID: deviceID], overrides: ["exp_checkout": 1, "exp_banner": 2], data: contextData)
context.setOverride(2, for: "exp_checkout")
context.setOverrides(["exp_banner": 1, "exp_search": 2])
context.setOverride(nil, for: "exp_banner")
context.setCustomAssignment(1, for: "exp_search")
let current = context.overrides // ["exp_checkout": 2, "exp_search": 2]setOverride(_:for:) and setOverrides(_:) update atomically, so they are safe from any thread.
Assigning the overrides property (context.overrides["x"] = 1) also works, but replaces the whole
dictionary: two threads doing it at the same time can overwrite each other.
Holdouts are set up in the ABsmartly dashboard and need no code. The context data lists them in
ContextData.holdouts, and each experiment names the holdouts covering it in Experiment.holdoutIds.
The SDK draws the unit's arm in each covering holdout (hashed with the experiment's unit type):
- Arm 0 holds the unit out: the experiment returns the control variant (
0) and its variables' control values, and publishes no exposure of its own. - In a holdout with three arms, arm 1 also holds the unit out of experiments that are not full-on; full-on experiments are assigned as usual. Every other arm leaves the experiment alone.
A unit held out by any covering holdout is held out. An exposing read of a covered experiment
publishes one exposure per covering holdout (its name and arm) the first time, even when the unit is
not held out; peeking (exposing: false) publishes nothing. An override and a matching assignment
rule still win over a holdout, and the experiment's own exposure is still published; a custom
assignment does not. Holdouts never apply to switchback experiments. A malformed holdout entry, or a
malformed id in holdoutIds, is ignored on its own.
// Held out by a covering holdout: 0, and only the holdout's exposure is published.
let variant = context.treatment(for: "exp_checkout")context.setAttribute("plan", to: "pro")
context.setAttributes(["age": 42, "country": "PT"])
try context.setUnit(.userID, to: "user-42")Audiences and assignment rules evaluate the attributes, plus the configured application and
environment names (an attribute you set with the same name wins). setUnit throws
ABsmartlyError.blankUnitUID, .unitAlreadySet or .closed, and leaves the unit unchanged.
context.track("purchase", properties: ["total": 19.99, "items": 2])try await context.publish()
try await context.refresh()
try await context.close()Exposures and goals are published publishDelay seconds after they are queued (0.1 s by default; a
negative value disables it). close() publishes whatever is pending; call it when the user's session
ends. A failed publish keeps the events queued for the next one.
for await event in context.events {
switch event {
case .ready: seen.append("ready")
case .exposure(let exposure): seen.append("exposure \(exposure.name)")
case .goal(let goal): seen.append("goal \(goal.name)")
case .error(let error): seen.append("error \(error)")
case .refresh, .publish: break
case .close: seen.append("close")
}
}Each access to context.events returns a new stream, which finishes after the context closes. To
see the events of every context, set configuration.eventLogger (.osLog writes them to the unified
log, with their contents, such as goal properties and attributes, marked private).
The async APIs throw ABsmartlyError (typed throws), so catch sees the cases directly:
do {
let context = try await client.context(units: [.deviceID: deviceID])
_ = context.treatment(for: "exp_checkout")
} catch .httpStatus(let code, _) {
print("ABsmartly is unavailable (\(code)); using defaults")
} catch {
print("ABsmartly failed: \(error.localizedDescription)")
}Reads never throw. A read before the context is ready, or after it is closed, returns the default
and emits an .error event.
The ABsmartlyUI product adds property wrappers that read the context from the environment:
import ABsmartlyUI
RootView().absmartlyContext(context)
struct CheckoutButton: View {
@Treatment("exp_checkout") var variant
@Variable("button.color", default: "blue") var color: String
var body: some View {
Button(variant == 1 ? "Buy now" : "Buy") {}
}
}Views re-render when the context becomes ready or refreshes. Without a context, or before it is
ready, the wrappers return 0 and the default.
Every snippet in this README is compiled by Tests/ABsmartlyUITests/DocSnippetTests.swift.
ABsmartly is the leading provider of state-of-the-art, on-premises, full-stack experimentation platforms for engineering and product teams that want to confidently deploy features as fast as they can develop them. ABsmartly's real-time analytics helps engineering and product teams ensure that new features will improve the customer experience without breaking or degrading performance and/or business metrics.