Example usage of the Swift SDK
1 min
After installing the Swift SDK, import the Optimizely library, get your project's datafile, and create a client. Use the client to evaluate flag rules like A/B tests and flag deliveries.
This example walks through the following three key steps:
- Evaluate a flag with the key product_sort using the decide method. This also sends a decision event to Optimizely to record that the user was exposed to the experiment.
- Run code based on the flag result. The SDK evaluates your flag rules and determines which variation the user is in. You can either:
- Check the flag's enabled state and read a configuration variable (sort_method) to determine which experience the user gets.
- Check the flag variation directly and run the corresponding control or treatment code.
- Track a conversion event called purchased to measure the experiment's impact. The trackEvent method ties the purchase back to the A/B test and sends it to Optimizely so it displays on your Experiment Results pageExperiment Results page.
// initialize an Optimizely client
optimizely = OptimizelyClient(sdkKey: "<Your_SDK_Key>")
// create a user and decide a flag rule (such as an A/B test) for them
let user = optimizely.createUserContext(userId: "user123", attributes: ["logged_in":true])
let decision = user.decide(key: "product_sort")
// did the decision fail with a critical error?
guard let variationKey = decision.variationKey else {
print("decide error: \(decision.reasons)")
return
}
// execute code based on flag enabled state
let enabled = decision.enabled
if (enabled) {
// get flag variable values
let sortMethod: String? = decision.variables.getValue(jsonPath: "sort_method")
// or:
let sortMethod: String? = decision.variables.toMap()["sort_method"] as? String
}
// or execute code based on flag variation:
if (variationKey == "control") {
// Execute code for control variation
} else if (variation.variationKey == "treatment") {
// Execute code for treatment variation
}
// Track a user event
try? user.trackEvent(eventKey: "purchased")