Feature flags

From gustavscirulis/snapgrid · View interactive version

Feature flags is an AI agent skill from the GitHub repository gustavscirulis/snapgrid. Generate feature flag infrastructure with local defaults, remote configuration, SwiftUI integration, and debug menu. Use when adding feature flags or A/B testing to iOS/macOS apps.

How to use this skill

Skill file

Feature Flags Generator

Generate a complete feature flag infrastructure with typed flag definitions, protocol-based providers (local, remote, composite), SwiftUI environment integration, an @Observable manager, and a debug menu for toggling flags at runtime.

When This Skill Activates

Use this skill when the user:

Pre-Generation Checks

1. Project Context Detection

2. Conflict Detection

Search for existing feature flag code:

Glob: **/*FeatureFlag*.swift, **/*FeatureToggle*.swift, **/*RemoteConfig*.swift
Grep: "FeatureFlag" or "FeatureToggle" or "RemoteConfig" or "isFeatureEnabled"

If existing feature flag code is found:

If a third-party SDK (Firebase, LaunchDarkly, etc.) is detected:

3. Required Capabilities

Feature flags require:

Configuration Questions

Ask user via AskUserQuestion:

  1. What features do you want to flag? (freeform)
  1. What flag value types do you need?
  1. What provider architecture?
  1. Include debug menu?
  1. Include SwiftUI environment integration?

Generation Process

Step 1: Determine File Locations

Check project structure:

Step 2: Create Core Files

Generate these files based on configuration answers:

  1. FeatureFlag.swift -- Flag enum with typed default values
  2. FeatureFlagService.swift -- Protocol defining provider interface
  3. LocalFeatureFlagProvider.swift -- UserDefaults-based provider with debug overrides
  4. RemoteFeatureFlagProvider.swift -- URL-based provider with disk caching (if remote or composite)
  5. CompositeFeatureFlagProvider.swift -- Combines local + remote; remote overrides local (if composite)
  6. FeatureFlagManager.swift -- @Observable manager for SwiftUI
  7. FeatureFlagEnvironmentKey.swift -- SwiftUI Environment integration (if requested)
  8. FeatureFlagDebugView.swift -- Debug toggle view (if requested)

Step 3: Generate Code from Templates

Use the templates in templates.md and customize based on user answers:

Output Format

After generation, provide:

Files Created

Sources/FeatureFlags/
├── FeatureFlag.swift                    # Flag enum with typed defaults
├── FeatureFlagService.swift             # Provider protocol
├── LocalFeatureFlagProvider.swift       # UserDefaults-based provider
├── RemoteFeatureFlagProvider.swift      # URL-based provider (if remote/composite)
├── CompositeFeatureFlagProvider.swift   # Local + remote combiner (if composite)
├── FeatureFlagManager.swift             # @Observable manager for SwiftUI
├── FeatureFlagEnvironmentKey.swift      # SwiftUI Environment key (if requested)
└── FeatureFlagDebugView.swift           # Debug toggle menu (if requested)

Integration Steps

1. Initialize the manager in your App struct or entry point:

import SwiftUI

@main
struct MyApp: App {
    @State private var featureFlagManager: FeatureFlagManager

    init() {
        // Local only
        let provider = LocalFeatureFlagProvider()

        // Or composite (remote overrides local)
        // let provider = CompositeFeatureFlagProvider(
        //     local: LocalFeatureFlagProvider(),
        //     remote: RemoteFeatureFlagProvider(
        //         endpoint: URL(string: "https://api.example.com/flags")!
        //     )
        // )

        _featureFlagManager = State(initialValue: FeatureFlagManager(provider: provider))
    }

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(featureFlagManager)
        }
    }
}

2. Use flags in your views:

struct ContentView: View {
    @Environment(FeatureFlagManager.self) private var flags

    var body: some View {
        VStack {
            if flags.isEnabled(.newOnboarding) {
                NewOnboardingView()
            } else {
                LegacyOnboardingView()
            }
        }
    }
}

3. Refresh remote flags (if using remote or composite):

// Refresh on app launch or periodically
Task {
    try await featureFlagManager.refresh()
}

4. Add debug menu (if generated, DEBUG builds only):

#if DEBUG
NavigationLink("Feature Flags") {
    FeatureFlagDebugView()
        .environment(featureFlagManager)
}
#endif

Testing Instructions

  1. Unit test providers independently: Each provider conforms to FeatureFlagService and can be tested in isolation.
  2. Mock provider for previews and tests:

```swift

final class MockFeatureFlagProvider: FeatureFlagService {

var overrides: [FeatureFlag: Bool] = [:]

func isEnabled(_ flag: FeatureFlag) -> Bool {

overrides[flag] ?? flag.defaultValue

}

// ... implement remaining protocol methods

}

```

  1. Debug menu: Run in DEBUG builds, navigate to the debug menu, and toggle flags to verify behavior.
  2. Remote provider: Use a local JSON file served via a test server or mock URLProtocol to test remote fetching.

Common Patterns

Boolean Flags (Kill Switches)

The most common pattern. Enable or disable a feature entirely.

if flags.isEnabled(.premiumPaywall) {
    PremiumPaywallView()
}

String Flags (Copy Variants / A/B Testing)

Use string values to serve different text or configuration strings remotely.

let welcomeMessage = flags.stringValue(.welcomeMessage) ?? "Welcome!"
Text(welcomeMessage)

Integer Flags (Thresholds / Limits)

Control numeric parameters like retry counts, page sizes, or rate limits.

let maxRetries = flags.intValue(.maxRetries) ?? 3

JSON Flags (Complex Configuration)

For structured configuration that changes server-side.

struct PaywallConfig: Codable {
    let title: String
    let trialDays: Int
    let showTestimonials: Bool
}

if let config: PaywallConfig = flags.jsonValue(.paywallConfig) {
    PaywallView(config: config)
}

Gradual Rollout

Combine feature flags with user segmentation.

// Server returns different flag values per user segment
// The flag is simply on/off from the client perspective
if flags.isEnabled(.newCheckoutFlow) {
    NewCheckoutView()
} else {
    LegacyCheckoutView()
}

Gotchas

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.