Movatterモバイル変換


[0]ホーム

URL:


Dev guideRecipesAPI ReferenceChangelog
Dev guideAPI ReferenceRecipesChangelogUser GuideGitHubDev CommunityOptimizely AcademySubmit a ticketLog InFeature Experimentation
Dev guide
All
Pages
Start typing to search…

Example usage of the Swift SDK

A brief code example of how to use the Optimizely Feature Experimentation Swift SDK to evaluate feature flags, activate A/B tests, or feature tests.

Once you have installed an SDK, import the Optimizely Feature Experimentation library into your code, get your Optimizely Feature Experimentation project's datafile, and instantiate a client. Then, you can use the client to evaluate flag rules, including A/B tests and flag deliveries.

This example demonstrates the basic usage of each of these concepts:

  1. Evaluate a flag with the keyproduct_sort using the Decide method. As a side effect, the Decide function also sends a decision event to Optimizely Feature Experimentation to record that the current user has been exposed to the experiment.

  2. Conditionally execute your feature code. You have a couple of options:

  • Fetch the flag enabled state, then check a configuration variable on the flag calledsort_method. The SDK evaluates your flag rules and determines what flag variation the user is in, and therefore which sort method variable they should see.
  • Fetch on the flag variation, then run 'control' or 'treatment' code.
  1. Use event tracking to track an event calledpurchased. This conversion event measures the impact of an experiment. Using the Track Event method, the purchase is automatically attributed back to the running A/B test for which we made a decision, and the SDK sends a network request to Optimizely Feature Experimentation using the customizable event dispatcher so Optimizely can count it in yourresults page.
// initialize an Optimizely clientoptimizely = OptimizelyClient(sdkKey: "<Your_SDK_Key>")// create a user and decide a flag rule (such as an A/B test) for themlet 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 statelet enabled = decision.enabledif (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 eventtry? user.trackEvent(eventKey: "purchased")

Updated 17 days ago



[8]ページ先頭

©2009-2025 Movatter.jp