Evaluate in your application
Swift SDK
The Swift SDK evaluates flags, variations and variables inside your Swift application, from a datafile it holds in memory, so no decision waits on the network. Its command line runs your project's test specs through this SDK, and an OpenFeature provider is available.
Install#
Add the package with Swift Package Manager:
.package(url: "https://github.com/featurevisor/featurevisor-swift2.git", from: "4.1.0")Then add the product to your target:
.product(name: "Featurevisor", package: "featurevisor-swift2")The SDK needs Swift 6.1 or later, which Xcode 16.3 and later include, and supports iOS 15, macOS 12, tvOS 15 and watchOS 8 or newer. Upgrading an existing application? Follow the Swift migration guide.
Create an instance#
Fetch a datafile and create an instance with it:
import Foundationimport Featurevisorlet datafileURL = URL(string: "https://cdn.example.com/featurevisor-all.json")!let initializationTask = Task { let (data, response) = try await URLSession.shared.data(from: datafileURL) guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else { throw URLError(.badServerResponse) } let datafileContent = try DatafileContent.fromData(data) try Task.checkCancellation() return createFeaturevisor( FeaturevisorOptions(datafile: datafileContent) )}let f = try await initializationTask.valuedefer { f.close() }print(f.isEnabled("checkout", ["userId": .string("user-4")]))This example closes the instance after one evaluation. In an application, keep it until shutdown. Await the task from your application's lifecycle and handle loading errors there, and keep its handle if loading may need to be cancelled with initializationTask.cancel().
Every option is optional, so an instance can start without a datafile and receive one later. FeaturevisorOptions takes them in this order:
| Option | Sets |
|---|---|
datafile | The datafile to evaluate |
context | The instance context |
logLevel, onDiagnostic | Diagnostics |
stickyFeatures, stickyVariables | Sticky values |
modules | Modules |
Create one instance and reuse it. On a server that handles many users, give each request a child instance. See the SwiftUI example application for an application that fetches a datafile and evaluates a flag, a variation and a variable.
Concurrency#
Featurevisor, its children and the OpenFeature provider are safe to use from concurrent callers. Module, diagnostic and event callbacks are @Sendable, so synchronize any mutable state they capture. Callbacks can call the instance again.
Context#
Context is a dictionary of attribute values. The instance keeps a context of its own, and each evaluation can add to it.
Set it when creating the instance:
let f = createFeaturevisor( FeaturevisorOptions( datafile: datafileContent, context: ["country": .string("nl")] ))Add to it later with setContext, or replace it with replace: true:
f.setContext(["userId": .string("user-4")])f.setContext( [ "userId": .string("user-2"), "country": .string("nl"), ], replace: true)Context passed to an evaluation is merged over the instance context for that call only:
let context: Context = [ "userId": .string("user-4"), "country": .string("nl"),]f.isEnabled("checkout", context)getContext() returns the instance context, and getContext(["country": .string("de")]) shows it merged with extra values without storing them.
Date conditions take portable timestamp strings with a time and an explicit time zone, not Foundation Date values. before and after are strict, and false for a value that is not a valid timestamp.
Check a flag#
isEnabled reads a flag. Dutch users have the new checkout:
let context: Context = [ "userId": .string("user-4"), "country": .string("nl"),]if f.isEnabled("checkout", context) { // show the new checkout}Get a variation#
getVariation returns the variation of a feature, or nil if the feature is disabled or has none:
if f.getVariation("pricing", context) == "treatment" { // show the new pricing}For user-4 it returns "control", and for user-2 it returns "treatment".
Get a variable#
getVariable reads a feature variable with a feature key and a variable key. For user-4, the netherlands rule sets the buy button's label to "Nu kopen":
let label = f.getVariable("buyButton", "label", context)With one key, the same method reads a global variable. supportEmail returns "[email protected]" for user-4:
let email = f.getVariable("supportEmail", context)A value is an AnyValue, such as .string("Nu kopen").
Typed methods#
Each typed method returns nil when the value has another type, and never parses a string. getVariableInteger returns nil for the string "1", and getVariableBoolean returns nil for "true".
| Method | Returns |
|---|---|
getVariableBoolean | Bool? |
getVariableString | String? |
getVariableInteger | Int? |
getVariableDouble | Double? |
getVariableArray | [AnyValue]? |
getVariableObject | [String: AnyValue]? |
getVariableJSON | AnyValue? |
Each reads a global variable with one key too:
let settings = f.getVariableObject("checkoutSettings", context)// ["currency": .string("EUR"), "paymentMethods": .array([.string("card")])]Composed variables#
Read a composed global variable like any other global variable. For a string compose alias, choose the getter for the source's type, such as getVariableString for an alias of supportEmail. It returns what the source's own getter returns, including decoded JSON and nil.
A composition is evaluated in this order:
- A sticky value for the whole variable, which skips everything after it.
- Root
conditions. When they miss, no source is read and no override runs. The result isdisabledValuewhen supplied, otherwisenil, with reason.conditionsUnmet. - The sources, with their own sticky values, the context and modules taking part as usual.
- The overrides, which run as they do for any global variable.
Compositions have no defaultValue or useDefaultWhenDisabled. With no override match, the reason is .variableComposed, and a match reports .variableOverrideRule, with variableOverridePaths listing every override that changed the value. Cycles, and chains of more than 256 dependencies, fail the whole evaluation.
Each step down a chain also checks the thread's remaining stack, so a chain too deep for the current thread fails with reason .error rather than crashing the app. Dispatch and Swift concurrency threads have 512 KB, enough for about 33 steps in a release build and fewer in a debug build, and lint warns about chains deeper than 32.
Default values#
Pass defaultVariationValue or defaultVariableValue in OverrideOptions for when an evaluation produces no value, such as a feature missing from the datafile:
let label = f.getVariable( "buyButton", "label", context, OverrideOptions(defaultVariableValue: .string("Buy")))A default counts as given whenever it is set, so .string(""), .int(0), .bool(false) and .null are all valid defaults.
Evaluate everything at once#
getFeatureEvaluations evaluates every loaded feature, or only the keys you pass:
let evaluations = f.getFeatureEvaluations(context, ["checkout", "pricing", "buyButton"])// checkout: enabled// pricing: enabled, variation "control"// buyButton: enabled, variation "treatment", variables ["label": "Nu kopen"]getVariableEvaluations does the same for global variables:
let variables = f.getVariableEvaluations(context, ["supportEmail", "checkoutSettings"])Leave out the keys to evaluate them all. To see what is loaded without evaluating anything:
getFeatureKeys()lists every feature in the datafile, enabled or not.getVariableKeys()lists global variables, andgetVariableKeys("buyButton")lists that feature's variables.hasVariations("pricing")istruewhen a feature has variations, andfalsefor an unknown feature.
Hand results from server to client#
Both results encode to the JSON shape sticky values take. A server can evaluate once per request and pass the results to its client, so the first render matches what the server saw. The JavaScript SDK's sticky values read them in a browser.
Sticky values#
Sticky values take precedence over the datafile. Use them to keep a user's result fixed, to answer before a datafile has loaded, or in unit tests:
let f = createFeaturevisor( FeaturevisorOptions( stickyFeatures: [ "checkout": EvaluatedFeature(enabled: true), "pricing": EvaluatedFeature(enabled: true, variation: "treatment"), ], ))A sticky feature can also set variables. Change sticky values later with setStickyFeatures and setStickyVariables. Both merge by default, and replace the whole dictionary with replace: true:
f.setStickyFeatures(["checkout": EvaluatedFeature(enabled: false)], replace: true)Update the datafile#
setDatafile gives the instance a newer datafile, decoded or as JSON text:
let accepted = f.setDatafile(datafileContent)f.setDatafile(json: jsonString)It returns true when the datafile is accepted, even if nothing changed, and false when it is rejected or the instance is closed. A rejected datafile leaves the previous one in place and is reported through diagnostics.
Merge or replace#
By default, the new datafile is merged into the current one:
- Its features, segments and global variables replace those with the same keys.
- Definitions it does not contain are kept.
- Its
revisionandschemaVersionare taken.
Pass replace: true to replace the current datafile entirely. Do this when refreshing a complete datafile, so definitions removed from it do not linger:
f.setDatafile(datafileContent, replace: true)Merging is what lets one instance hold datafiles for several targets, loaded as each part of the application needs them. See Loading datafiles on demand.
Refresh on an interval#
The SDK starts no timer of its own. Keep one refresh task per instance, which waits five minutes after each attempt, so slow requests cannot overlap:
let refreshTask = Task { while !Task.isCancelled { do { let (data, response) = try await URLSession.shared.data(from: datafileURL) guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else { throw URLError(.badServerResponse) } let datafile = try DatafileContent.fromData(data) try Task.checkCancellation() f.setDatafile(datafile, replace: true) } catch { if Task.isCancelled { return } print("Could not refresh datafile: \(error)") } do { try await Task.sleep(nanoseconds: 5 * 60 * 1_000_000_000) } catch { return } }}A failed fetch keeps the previous datafile. Before closing the instance, cancel the task and await it with refreshTask.cancel() and await refreshTask.value. Each accepted update emits datafile_set.
Child instances#
A server handles many users at once, so give each request a child with its own context:
let child = f.spawn([ "userId": .string("user-4"), "country": .string("nl"),])child.isEnabled("checkout")- The child copies the parent's context keys when it is spawned, and its own values win. Keys the parent adds later still reach it.
- Sticky values are not inherited. Pass them in
SpawnOptionswhen the child needs some. - A child has the parent's evaluation methods, plus
getContext,setContext,setStickyFeatures,setStickyVariables,onandclose. close()removes the child's listeners, including the ones it registered on its parent.
Events#
on subscribes to an event and returns a function that unsubscribes, safe to call more than once. The callback receives an EventPayload, whose params hold the details.
datafile_set#
Emitted for every accepted datafile:
let unsubscribe = f.on(.datafileSet) { payload in // payload.params["revision"], ["previousRevision"], ["revisionChanged"], ["replaced"], // ["features"], ["variables"] and ["segments"] // evaluate the listed features and variables again}unsubscribe()replaced says whether the datafile replaced the previous one or merged into it. features and variables list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. Evaluate those again and you have everything that changed.
segments lists the segments whose definitions were added, changed or, on a replace, removed. If a new datafile has the netherlands segment take Belgium too, segments is ["netherlands"], and features and variables include checkout and supportEmail, whose conditions read it. The first datafile lists every feature, global variable and segment. sections lists the changed entries of each datafile section, such as schemas.
context_set#
Emitted by setContext as .contextSet:
f.on(.contextSet) { payload in // payload.params["context"] is the new instance context // payload.params["keys"] lists the top level keys whose values changed}keys compares values, so a key set again to the value it already holds is not listed. Starting from the instance context ["userId": "user-4", "country": "nl"]:
f.setContext([ "country": .string("de"),])// keys: ["country"]f.setContext([ "country": .string("de"), "plan": .string("paid"),])// keys: ["plan"]f.setContext([ "userId": .string("user-4"), "country": .string("de"),], replace: true)// keys: ["plan"]A replace also lists the keys it removed, as plan above. Objects and arrays compare item by item, and numbers by value, so .int(30) and .double(30) are the same. keys is sorted.
sticky_features_set#
Emitted by setStickyFeatures as .stickyFeaturesSet, with features, every feature that had a sticky value before the call or has one after it, and replaced.
sticky_variables_set#
Emitted by setStickyVariables as .stickyVariablesSet, with variables and replaced.
error#
Emitted for every diagnostic at .error, with the diagnostic.
Diagnostics#
The SDK reports what happens during evaluation as diagnostics, at one of five levels: .fatal, .error, .warn, .info and .debug. By default, those at .info and above go to the console with a [Featurevisor] prefix.
.debug shows how each value was evaluated, which helps when a result surprises you. Set the level when creating the instance, or later with setLogLevel. To send diagnostics somewhere other than the console, pass a handler:
let f = createFeaturevisor( FeaturevisorOptions( logLevel: .warn, onDiagnostic: { diagnostic in // send diagnostic.level, code, message and details to your observability system } ))f.setLogLevel(.debug)Every diagnostic has a level, a code, a message and a details dictionary. Values about an evaluation, such as featureKey, variableKey, reason and evaluation, are in details. module, moduleName and originalError say where an error came from, when known.
Evaluation errors#
conditions_parse_error is an .error diagnostic for malformed stringified conditions. It fires once per selector per datafile load, on first read for v4 datafiles and during setDatafile for v3 datafiles. Its details contain conditions with the raw string, entityType and entityKey.
The whole malformed selector evaluates to false, even under not, while other entities keep working and setDatafile returns true for an otherwise valid datafile. A malformed root gate is unmet and reports .conditionsUnmet.
Dependency cycles fail the whole evaluation with reason .error. SDK evaluation errors return the ordinary false or nil result, and other entities keep working.
Evaluation details#
The evaluate methods return how a value was reached, not only the value:
f.evaluateFlag("checkout", context: context)f.evaluateVariation("pricing", context: context)f.evaluateVariable("buyButton", "label", context: context)f.evaluateVariable("supportEmail", context: context)For user-4, evaluateFlag returns an Evaluation with these fields set:
| Field | Value |
|---|---|
type | .flag |
featureKey | "checkout" |
reason | .rule |
bucketKey | "user-4.checkout" |
bucketValue | 89312 |
ruleKey | "netherlands" |
enabled | true |
Every evaluation has a type and a reason. The others are nil unless they apply:
featureKey,nilfor global variablesbucketKeyandbucketValue, from 0 to 100,000, and theruleKeythat matchedenabled,variationandvariationValuevariableKey,variableValue,variableSchemaand theglobalVariabledefinitionvariableOverrideKeyandvariableOverrideIndexwhen a keyed override matched, andvariableOverridePathfor a nested onevariableOverridePaths, every override path matched in order, for accumulating overrides. The singular fields describe the last matchconditionswhen a root gate stopped the evaluationerrorwhen evaluation failed
Evaluation reasons#
Test specs can assert them, written as JSON writes them, which is each case's raw value.
| Reason | Meaning |
|---|---|
.featureNotFound | The feature is not in the datafile |
.disabled | The feature is disabled |
.noVariations | A variation was requested from a feature without variations |
.variationDisabled | A disabled feature returned its disabledVariationValue |
.variableNotFound | The feature variable or global variable is not in the datafile |
.variableDefault | The variable returned its default value |
.variableComposed | A global variable read its composition sources with no override match |
.variableDisabled | A disabled feature returned the variable's disabled value |
.variableOverrideVariation | A feature variable override matched inside a variation |
.variableOverrideRule | A feature variable override or global variable override matched |
.conditionsUnmet | Root conditions did not match. See conditions |
.noMatch | No rule, allocation or variation matched, or the bucket fell outside the rollout |
.forced | A force entry supplied the result |
.sticky | A sticky value supplied the result |
.rule | A matching rule supplied the result |
.allocated | Bucketing allocated the result |
.error | Evaluation failed. See error |
Modules#
A module hooks into evaluation. It can change the context before an evaluation, change the result after it, or decide how users are bucketed. Pass the closures you need to FeaturevisorModule:
let audit = FeaturevisorModule( name: "audit", setup: { api in print("Ready for revision \(api.getRevision())") }, beforeEvaluation: { options in // options.type, featureKey, variableKey and dependencies.context var updated = options updated.dependencies.context["plan"] = .string("paid") return updated }, // between 0 and 100,000 bucketValue: { options in options.bucketValue }, afterEvaluation: { evaluation, _ in evaluation }, close: { // clean up when the instance closes })beforeEvaluation and afterEvaluation run for flags, variations and both kinds of variable, every module in registration order, and globalVariable on the options says which kind a variable is. A module without evaluation closures, such as a package's, costs evaluations nothing.
beforeEvaluation also runs when a schema validates, with type .entry and entry naming the schema, its type schema and its key, instead of a featureKey, so context it adds reaches the schema's conditions too. afterEvaluation does not run then, since a validation's result is not an evaluation. Check type before reading the keys.
The before evaluation and after evaluation phases each use the module membership at the start of that phase, and the bucket key and bucket value phases each use their own. Adding or removing a module during a phase does not change the iteration already in progress.
Dependency evaluations#
Conditions and composition members are evaluated through modules too. Their options carry dependencyOf, naming the requesting evaluation, and dependencyPurpose, "condition" for an eligibility check and "composition" for a consumed member value. Direct calls have neither.
When tracking consumed evaluations, skip eligibility checks, not every read with dependencyOf, since a variation read through a composition can be an experiment exposure. Within one call, repeated reads with the same inputs and purpose are memoized, so callbacks can run fewer times than there are reads. Return the same result for the same input during one evaluation, and pass values that change through the context.
Register a module#
Pass modules when creating the instance, or add them later:
let f = createFeaturevisor( FeaturevisorOptions(modules: [audit]))let remove = f.addModule(tracking)// laterremove?()f.removeModule("audit")addModule returns nil for a module whose name is already registered, which reports duplicate_module.
Read the datafile from a module#
A package, such as schemas, reads the datafile through the FeaturevisorModuleApi setup receives:
getEntry(section, key)returns an entry of a section, a top level key besides Featurevisor's own whose value is an object, such asschemas, andgetEntryKeys(section)lists a section's keys.matchConditions(_:context:options:)answers the package's own conditions with the instance's engine, segments and feature leaves included.MatchConditionsOptions.readersanswer leaves only the package knows, such asinput.evaluate(PackageEvaluationRequest(type:key:context:)) { scope in ... }evaluates the package's own entry as a getter evaluates a flag. Every module'sbeforeEvaluationruns first, with type.entryandentrynaming the package's type and key, and the conditions the closure answers withscope.matchConditions(_:readers:)read the context the modules leave, in one dependency session.
Feature and variable leaves reach modules as dependencies, with dependencyOf.type .entry and dependencyOf.entry naming the package's entry. The API holds the instance weakly, so keep the instance for as long as a module uses it.
Schemas#
Schemas validate data against the schemas your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as @featurevisor/schemas in JavaScript.
Schemas are experimental, so their API may change in a minor release, as in JavaScript.
Create a schemas instance#
They are the FeaturevisorSchemas library product of the same package:
.product(name: "FeaturevisorSchemas", package: "featurevisor-swift2")Create it from the SDK instance. Call it s, as the SDK instance is f:
import Featurevisorimport FeaturevisorSchemaslet s = Schemas(f)It holds no copy of the schemas. Every call reads the datafile f has now, so a new datafile applies at the next validation. It and its handles are safe to share between threads and tasks.
Validate a value#
struct SignUp: Codable { var email: String var displayName: String var country: String?}let result = s.validate("signUp", value)if !result.isValid { // show result.issues beside the form's fields}s.validate(key, value, context:)returns aValidationResultwith itsissues. It never coerces, fills defaults or strips keys.- A value is an
AnyValue, or anythingEncodable, such as aCodablestruct, whose optional properties leftnilcount as absent. s.isValid(key, value)returns a boolean, ands.parse(key, value)returns the value or throws aSchemaValidationErrorwith the issues.contextis merged over the instance's, for the conditions a schema's rules read.- A validation runs as the schema's own evaluation, so a module's
beforeEvaluationsees it, with.entrynaming the schema, and context the module adds reaches every condition, as it does for flags. s.keyslists the schemas the datafile has, ands.has(key)says whether it has one.
A key the datafile does not have fails closed, with one schemaNotFound issue, and a schema_not_found diagnostic at .warn, once per key and datafile revision.
Read the issues#
Every SchemaIssue has a message, a path of object keys and array indices, the code of the rule that failed, its params, and the schema validated.
Validation reports every issue it finds, so a form can mark every field at once. An issue about a field with a title carries it in params["title"], and one whose rule a mutation set names it in mutation.
| Code | Raised when |
|---|---|
type | The value has another type |
const, enum | The value is not one allowed |
minimum, maximum | A number is out of range |
minLength, maxLength | A string is too short or too long |
pattern, format | A string has the wrong shape |
minItems, maxItems | An array has too few or too many items |
uniqueItems | An array repeats an item |
required, additionalProperties | A key is missing, or there is one it does not allow |
oneOf | No branch matches, or more than one does |
refine | An issues entry matches, or a check in code fails |
refineError | A check in code fails with an error, or the schema cannot be applied |
schemaNotFound | The datafile has no such schema or field |
result.flattened groups the messages by field, in the shape of Zod's flattenError, with formErrors and fieldErrors such as ["displayName": ["..."]].
Get a handle#
s.get("signUp") gives the schema's handle:
let signUp = s.get("signUp")A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application.
| Member | What it is |
|---|---|
validate, isValid, parse | As on s, without the key |
field(_:) | The handle of one field, such as field("displayName") |
fields | An object's fields' handles, in order, each with its name |
constraints, fieldConstraints | HTML validation attributes, fieldConstraints by field path on an object, below |
options, fieldOptions, option(_:) | Its choices, fieldOptions by field path on an object, and one choice by value |
renderAs | What its rules say the field renders as, such as .select |
annotations | Its annotations |
withInput(_:context:) | The same handle with an input |
reads | The fields its rules' conditions read |
subscribe(_:) | A call when a new datafile changes the schema |
key, path, name | The schema's key, and the field's path and own name |
field takes a field name as form libraries write it: address.city, items.0.name or items[0].name, and items[].name for every item alike. It follows references and stops at oneOf. A path the schema lacks fails closed with schemaNotFound and its field, and reports no schema_not_found diagnostic, since the schema itself is there. A field's handle always validates the value it is given, and JSON null is a value. Swift has no "no value" for it, so the rule that a field with no value reads as absent, as in JavaScript, has nothing to apply to here. Validate the whole object to have a missing field reported as required. A key a schema's required lists counts as required whether or not properties lists it, as constraints.required and required issues both say, and required applies to an object with no properties at all.
Read constraints and choices#
constraints are named after HTML attributes:
let constraints = signUp.field("displayName").constraints// required: true, minLength: 2, maxLength: 40required, when the key is required, so an input left empty failsminLengthandmaxLength, from the same rules on a stringminandmax, fromminimumandmaximumon a numberstepof 1, for anintegermultiple, for an array, such as a multiple select
options lists a field's choices in the order of its rules, each with what its annotations say, and option(_:) finds one, for showing a value saved earlier:
let country = signUp.field("country")country.options // nl, de and becountry.option(.string("nl"))?.title // "Netherlands"country.option(.string("fr")) // nilA schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. renderAs answers the switch every generic form writes, from the field's rules alone: .text, .dateTime, .version, .number, .boolean, .select, .multiselect, .object or .list. RenderAs is a struct with static members, as IssueCode is, so match it with switch and a default, since a later release can add a value. Your own annotation, such as input: select, still wins over it.
Read annotations#
A handle's annotations are its node's own, and fields gives an object's fields in its order:
signUp.annotations["title"] // .string("Create your account")signUp.fields.map(\.path)// ["displayName", "email", "country"]default is the value a form starts a field with, and a handle from withInput has the one a mutation sets. Fields an order annotation leaves out come after it, in name order by Unicode code point, as in every SDK. A field or schema the datafile lacks has no annotations. Annotations on Schemas writes them.
Follow the values typed so far#
A handle's constraints and choices describe the schema's own rules, which no condition changes. withInput(_:) gives the same handle with an input, such as a form's values, with the mutations that match it applied, so a tax ID shows as required once a business account is chosen:
let values: [String: AnyValue] = [ "accountType": .string("business"), "country": .string("nl"),]signUp.field("taxId").constraints.required // falsesignUp.withInput(values).field("taxId").constraints.required // trueEvery member follows the input, at every depth. reads lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes.
Choose the messages#
SchemasOptions words every schema's issues, per code, as a template or with .custom { params, info in ... }:
let s = Schemas(f, options: SchemasOptions( messages: [.required: "This field is required"]))HandleOptions(messages:) with s.get(_:options:) words one form, by field and code. For each issue, the first of these that words it wins:
- A check in code's own message, then the form's.
- The schema's own, and then the
messageof its issues entry. - The application's, from
SchemasOptions. - The default, in English.
translator on SchemasOptions gets each issue, with the message chosen, and returns what the issue says, or nil to keep it. With translations, the messages hold keys, such as errors.required, and translator turns each into text.
Check in code#
Some checks need your application, such as whether a display name is taken. Give them to a handle in HandleOptions(refinements:), each a Refinement with a key and a check, and the path it checks, a message and reads as it needs them:
let signUp = s.get("signUp", options: HandleOptions( refinements: [ Refinement("nameAvailable", path: "displayName", message: "That display name is taken", asyncCheck: { value, _ in try await accounts.isNameAvailable(value.asString() ?? "") }), ]))let result = try await signUp.validate(request)- A check gets the value at its path, and a
CheckInfowith the wholeinputand thecontext. It returnstruewhen the value passes. - It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your server.
- Without a
path, the check gets the whole value, and runs only when the value has no issue at all.readsnames other fields whose issues hold it back too, such asitemsfor a check of an order's total. - Its issue has code
refineand therefineparam"nameAvailable", with the field's title. A check that throws givesrefineError, validation fails closed, and oneschema_check_errordiagnostic at.errorsays which check of which schema threw, once per schema and check for each datafile revision, with itsschemaKey,checkandpathindetailsand the error asoriginalError. A check cancelled with its task reports nothing. A check in a field's handle gets the field's value as itsinput, not the whole object, unless the handle is a view from the schema's root. - The synchronous
validateruns checks in order. The asynchronous one runs them concurrently in a task group and keeps their issues in order.check:answers at once, andasyncCheck:answers later, such as one asking a server. In an async contextvalidatewaits for every check, and cancelling the task cancels them. Outside one,validateanswers at once, and a check that answers later reportsrefineError.
Options from your application#
Some lists only your application can answer for, such as cities for a city field. Give a handle an OptionSource in HandleOptions(optionSources:), with a key, a path, and a search, a lookup or both:
let cities = OptionSource( "cities", path: "city", reads: ["country"], message: "Choose a city from the list", search: { query, info in try await cityIndex.search(country: info.read("country"), query) }, lookup: { city, info in cityIndex.find(country: info.read("country"), city) })let city = s.get("signUp", options: HandleOptions(optionSources: [cities])) .withInput(["country": AnyValue.string("nl")]) .field("city")let suggestions = try await city.search("am")// Amsterdam and Amersfoortsearchreturns values, or objects with avalue. A handle'ssearchpasses it the values given towithInput, so the cities follow the country.canSearchsays whether a field has one.lookupreturns what the source says about a value, an object with its fields when found, ornilwhen there is none. A handle'slookup(_:)returns the schema's own choice first, then the source's. PassasyncLookup:for one that answers later.- Validation runs
lookupas a check in code, after the schema's rules, only for a value that is there, and not while a fieldreadsnames has an issue. A value it cannot find has codeenum, worded by its message.
Validate on the server#
parse validates a request before it reaches your code, with the issues when it fails:
do { let signUp = try s.parse("signUp", request) try await accounts.create(signUp)} catch let error as SchemaValidationError { // respond with 422 and error.flattened}A rule changed in your project reaches the apps and the server at their next datafile, so the two never disagree.
Listen for changes#
subscribe calls back when a new datafile changes the schema, and returns a function that stops it:
let stop = s.get("signUp").field("country").subscribe { Task { @MainActor in model.reloadChoices() }}A datafile whose schema is unchanged calls nothing. s.close() stops every listener the instance started and removes its module from the Featurevisor instance.
Patterns#
Schema patterns are JavaScript regular expressions with the u flag, and they mean the same here: $ is the end of the value, \s is JavaScript's whitespace, and . reads an emoji as one character, as lengths do. A pattern that does not compile with u, such as [a-z\_], fails every value with one schema_pattern_unsupported diagnostic. A mutation whose operations cannot be applied fails the value with refineError and one schema_mutation_error diagnostic, and so does a value nested more than 128 references deep, such as a tree whose nodes each reference the tree's schema, with schema_reference_depth. The 128th level passes and the 129th fails closed. Each of these diagnostics, and schema_not_found, is reported once per datafile revision, and again after a new datafile.
A type the package does not know fails every value with a type issue. Strings compare by Unicode scalars, as JavaScript compares code units, so const: "\u{E9}" rejects e\u{301}. Swift dictionary keys still treat canonically equivalent strings as one, so two field names that differ only so cannot both be told apart. Where a list needs an order, such as reads and the fields without an order annotation, names sort by Unicode scalars, since Swift keeps no order of an object's properties.
Close#
close() removes event listeners and closes modules, on the instance and on a child:
f.close()Closing more than once does nothing more. An evaluation already in progress finishes with the datafile it read.
OpenFeature#
The package exposes FeaturevisorOpenFeature as a separate library product using OpenFeature Swift 0.7.0. Targets using it should declare both package dependencies:
.package(url: "https://github.com/featurevisor/featurevisor-swift2.git", from: "4.1.0"),.package(url: "https://github.com/open-feature/swift-sdk.git", .upToNextMinor(from: "0.7.0"))Then add the products needed by that target:
.product(name: "Featurevisor", package: "featurevisor-swift2"),.product(name: "FeaturevisorOpenFeature", package: "featurevisor-swift2"),.product(name: "OpenFeature", package: "swift-sdk")Core consumers need only the Featurevisor product. OpenFeature 0.7 uses specification reason strings such as TARGETING_MATCH and ERROR. Its logging APIs accept OpenFeatureLogger. Applications using swift-log can add the optional OpenFeatureSwiftLog product and wrap their logger with SwiftLogLogger.
import Featurevisorimport FeaturevisorOpenFeatureimport OpenFeaturelet provider = FeaturevisorOpenFeatureProvider( options: FeaturevisorOptions(datafile: datafile))await OpenFeatureAPI.shared.setProviderAndWait( provider: provider, initialContext: ImmutableContext(targetingKey: "user-4"))let client = OpenFeatureAPI.shared.getClient()let enabled = client.getBooleanValue( key: "checkout", defaultValue: false)Use checkout for a flag, checkout:variation for its variation, buyButton:label for a feature variable, and variable:supportEmail for a global variable. Boolean variables use the boolean resolver. Lists, structures, and JSON variables use the object resolver.
The provider maps Featurevisor values to OpenFeature resolvers:
| Key | Resolver |
|---|---|
feature | Boolean flag |
feature:variation | String variation |
feature:variable | Resolver matching the variable schema |
variable:key | Resolver matching the global variable type |
Integer variables can be resolved with either the integer or double resolver. Non-finite doubles are rejected with TYPE_MISMATCH. Invalid JSON variables also return TYPE_MISMATCH and the caller's default value.
OpenFeature's targeting key maps to userId by default. targetingKeyField, keySeparator, variationKey, and globalVariablePrefix can customize the mapping. The global variable prefix defaults to variable and cannot contain the separator. Call provider.close() when the application owns the provider lifecycle and is finished with it. The upstream Swift EvaluationContext exposes getTargetingKey() as a nonoptional string and its asMap() does not include the targeting key. It returns an empty string for both an omitted key and an explicitly empty key, so this provider cannot distinguish those cases. An empty key therefore leaves an existing value in the configured targeting field unchanged. Callers requiring empty key override semantics must set that field explicitly as an attribute, such as "userId": "". Clear any inherited nonempty targeting key at its source first, since it would overwrite that attribute again. A narrower empty key may not clear it.
Initialize the provider from raw JSON:
let provider = FeaturevisorOpenFeatureProvider( options: FeaturevisorOptions(logLevel: .warn), datafileJSON: json)Malformed JSON returns the OpenFeature PARSE_ERROR code with Could not parse datafile. The provider keeps returning that error until a valid datafile is set through provider.featurevisor.setDatafile(...). Successful replacement clears the parse error.
Reuse an existing Featurevisor instance:
let featurevisor = createFeaturevisor(FeaturevisorOptions(datafile: datafile))let provider = FeaturevisorOpenFeatureProvider(featurevisor: featurevisor)The caller owns an instance passed this way. Closing the provider does not close it. Call featurevisor.close() when every consumer is finished with it. When the provider creates the instance from options, the provider owns and closes it. If both are supplied, featurevisor takes precedence over options.
Featurevisor evaluation reasons map to OpenFeature reasons:
| Featurevisor reason | OpenFeature reason |
|---|---|
forced, sticky, rule, variable_composed, variable overrides | TARGETING_MATCH |
allocated | SPLIT |
disabled flag, variation, or variable, conditions_unmet | DISABLED |
| no match, variable default | DEFAULT |
| missing feature, variable, or variations | ERROR with FLAG_NOT_FOUND |
| evaluation error | ERROR with GENERAL |
Resolution metadata includes featureKey when present, featurevisorReason, schemaVersion, and revision. It also includes variableKey, ruleKey, bucketKey, bucketValue, forceIndex, variableOverrideIndex, variableOverrideKey, and variableOverridePath when those values are available. Variation resolutions populate OpenFeature's variant field.
The provider forwards OpenFeature tracking calls to onTrack. Closing a provider it owns closes Featurevisor modules and subscriptions. Closing a provider created with a caller-owned Featurevisor instance only removes provider subscriptions.
The base Featurevisor product does not compile or link OpenFeature provider code into an application target. Swift Package Manager still resolves the package-level swift-sdk dependency because both products share one package manifest. Projects that require dependency-download isolation would need the provider in a separate repository.
Invalid initial JSON leaves the provider in error status, independently of the diagnostic log level. Swift registration completes without throwing. A valid datafile update restores readiness. Direct featurevisor.setContext calls emit configuration change events for both owned and supplied instances, without starting a second OpenFeature context reconciliation. Closing the provider detaches these subscriptions and closes only an owned instance.
See the OpenFeature provider guide for resolution reasons, errors, metadata, tracking, lifecycle, and providers for other languages.
CLI usage#
Build the executable from this SDK repository with Swift 6.1 or later:
swift build --product featurevisorThe native test runner requires Node.js 24 or later. Install the Node.js CLI in your Featurevisor project:
npm install --save-dev @featurevisor/cli@^4.0.0The native CLI supports test, benchmark and assess-distribution. Node.js remains responsible for parsing definitions, listing tests through the execution protocol, expanding matrices and generating datafiles through npx featurevisor. Evaluations run through this Swift SDK. Use the Node.js CLI directly for authoring commands such as init, lint and build. The SDK runtime has no Node.js dependency.
Options use kebab case, such as --project-directory-path. The camelCase forms from earlier releases still work, and --root-directory-path is an alias for --project-directory-path. Pass values as --name=value or --name value. Repeat --target to select several targets in order. Run <command> --help to list every option.
Quote JSON and paths containing spaces as a single shell argument. Duplicate targets are evaluated once, at their first position. Extra positional arguments and unknown options are rejected.
Test#
swift run featurevisor test \ --project-directory-path=/path/to/featurevisor-project \ --only-failuresSee Testing for authoring specs and Checks for check syntax and operators.
The Node.js CLI owns definition parsing, builds, linting and execution expansion. Swift consumes its version 1 execution envelope and evaluates through the native SDK. Run npx featurevisor lint separately. test does not run lint automatically. Segment specs and checks use SDK gates with the selected datafile, context, fixed bucket and sticky state. Selected Target segment specializations remain authoritative, with compiled execution definitions restoring missing segments. Attribute only segment chains can run without an environment. Feature or variable dependencies require the selected datafile. Check references, including transitive dependencies and child checks, are validated before getters run. Synthetic segment gates are excluded from coverage.
Useful test options:
--key-pattern=<pattern>and--assertion-pattern=<pattern>filter tests.--entity-type=scenarioselects scenarios, and--entity-type=schemaschema specs, which validate their values withFeaturevisorSchemasas the JavaScript CLI does.--set=<set>selects one project set. Omitting--setruns all sets.--case=<id>reruns one expanded case. Copy the opaque ID or rerun command from a failure report.--json --prettyproduces an indented JSON report.--coveragereports observed rule and override selections.--uncoveredlists features and global variables without associated specs.--only-failures,--quiet,--verboseand--show-datafilecontrol diagnostic output.
Benchmark#
The examples below use a project without environments. Add --environment=<name> if your project configures environments. In a sets project, omit --set to run every set or pass --set=<name>. Repeat --target=<key> to evaluate specific target datafiles. The Node.js CLI validates these options and builds the datafiles. Swift evaluates them. Replace checkout with a feature defined in your project.
swift run featurevisor benchmark \ --project-directory-path=/path/to/featurevisor-project \ --feature=checkout \ --context='{"country":"nl"}' \ --n=1000Use --variation for a variation or --variable=<key> for a feature variable. Omit --feature to benchmark a global variable. Do not combine --variation with --variable. See Benchmarking.
Assess distribution#
swift run featurevisor assess-distribution \ --project-directory-path=/path/to/featurevisor-project \ --feature=checkout \ --populate-uuid=userId \ --n=1000Repeat --populate-uuid=<key> or --populate-uuid <key> to generate UUID values for multiple context attributes. --n and -n both accept a positive integer and default to 1000 evaluations in this native CLI. See Assess distribution.
GitHub repositories#
- SDK: featurevisor/featurevisor-swift2
- Example application: featurevisor/featurevisor-example-swift
- SwiftUI iOS example application: featurevisor/featurevisor-example-ios

