How to use feature flags in Swift
Tags: featuremanagement, featureflags, swift, configcat
Published: 2023-01-21 12:49:51

Have you ever wanted to add a new feature to your iOS app with the option to roll it back quickly if things go wrong? Feature flags can help! With feature flags, you can deliver new features remotely with the click of a button without having to republish your app.

## Understanding feature flags

A Feature flag is a boolean marker that can be attached to a new feature/component you want to deploy. It can then be used in a conditional statement in your code to display a new feature when its value is set to true. You can create and use feature flagging in [many programming languages](https://configcat.com/docs/sdk-reference/overview/). Let's examine how we can deploy a new feature in a Swift IOS app using a feature flag.

### Prerequisites

Take a moment to explore the prerequisites listed below to follow along:

- A Mac computer
- [The latest version of Xcode](https://developer.apple.com/xcode/)
- Basic [Swift knowledge](https://developer.apple.com/swift/)

With that covered, let's turn our attention to the [sample app](https://github.com/configcat-labs/feature-flags-in-swift-ios-sample) and discuss how we can implement feature flagging.

### Using the sample app

![feature flags in swift secondary cover photo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uh3eiws0wjztnkzftunc.png)

**1.** Clone the [code repository](https://github.com/configcat-labs/feature-flags-in-swift-sample)

**2.** Open the project with Xcode

**3.** You should be able to see a preview of the app by selecting **PlaylistsView** in the left sidebar

![Screenshot of sample app with feature flags turned on](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ihax807sddtuibrhwtsb.png)

Consider the red **Upvote** button in the playlist card as the new feature to be rolled out. To deploy this feature I'll link it to a feature flag. In this way, I can toggle it on or off remotely without editing or redeploying the code. In order to do this, I am going to use [ConfigCat's feature flag service](https://configcat.com/).

### Integrating with ConfigCat

**1.** To use ConfigCat, you'll need to [sign up for a free account](https://app.configcat.com/signup)

**2.** In the dashboard, create a feature flag with the following details:

![Adding a feature flag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zzhrcdkv5zxaz8dp2k55.png)

**3.** You'll need to add ConfigCat's Swift SDK as a package dependency into your app as mentioned below. With this SDK, the app will be able to access your ConfigCat dashboard and probe the feature flag's status. 

**a.** Select **File**, **Add Packages**... as shown below

![Selecting Add Packages](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2d1h8nffulms654szjqu.png)

**b.** With the **Apple Swift Packages** collection selected, enter **https://github.com/configcat/swift-sdk** in the search bar on the top right to find the package. Then click the **Add package** button at the bottom right.

![Adding ConfigCat Swift SDK package](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jglhgn0kgtlhu6avdywr.png)

**4.** Import ConfigCat, then create the client with your SDK key. You should keep this key private and outside of your code base.

```swift
import ConfigCat

let client = ConfigCatClient.get(sdkKey: "YOUR_CONFIGCAT_SDK_KEY") { options in
    options.pollingMode = PollingModes.autoPoll(autoPollIntervalInSeconds: 15)
}

```

**5.** Create an **ObservableObject** class called **Features**. Since the ObservableObject is reactive in nature, the app will only re-render the component (in our case, the Upvote button) that relies on it whenever its value changes. I've also added an **init** method inside the class with code to probe the status of the feature flag from ConfigCat's dashboard and update the **canShowUpvote** property when it initializes.

```swift
class Features: ObservableObject {
   @Published var canShowUpvote = false
    init() { 
        client.getValue(for: "canshowupvote", defaultValue: false) { isUpvoteFeatureEnabled in
            if isUpvoteFeatureEnabled {
                self.canShowUpvote = true
            }
        }
       
    }
}

```

**6.** I'll add a **StateObject** variable inside the view that instantiates the class we created above. This will be used in the next step to check the status of the **canShowUpvote** property.

```swift
struct PlaylistCard: View {
  // ...
  @StateObject var appFeatures = Features()
    
  var body: some View {
      // ...
  }
}
```

**7.** Finally, add an if statement to render the **Upvote** button when the value of the **canShowUpvote** property is true:

```swift
    var body: some View {
      VStack{
        // ...
        Spacer()
        if appFeatures.canShowUpvote {
            Button("Upvote") {}
        // ...
        }
      }
    }
  }
```

You can find the complete code [here](https://github.com/configcat-labs/feature-flags-in-swift-ios-sample/blob/master/Playlister/Views/PlaylistCard.swift).

## Pulling it all together

**1.** Head over to the ConfigCat dashboard and **turn off** the feature flag:

![Turning off the feature flag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vf1wyiskpimkpodwd21e.png)

**2.** Restart the app preview and you should no longer see the **Upvote** button

![Sample app with feature flag turned off](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/92br5d8holhjaycjp3ru.png)

**3.** That's it!

Despite this being a standard approach, deploying a new feature to your entire user base may not always be ideal. Within your ConfigCat dashboard, you can target feature releases based on a user's demographics and characteristics. It is possible, for instance, to release your new feature only to British users over 23 years old.
 
## Conclusion

As we’ve discussed, It is a good idea to use feature flags as part of your iOS feature releases. By utilizing ConfigCat's feature flagging solution, you can streamline and simplify this process. Using the 10-minute trainable interface, your team can get started with feature flags quickly. In my opinion, feature flags have always proven to be useful in development workflows such as progressive feature rollouts, canary deployments, and A/B testing.

## Stay tuned

For more awesome posts like these and other announcements, follow ConfigCat on [Twitter](https://twitter.com/configcat), [Facebook](https://www.facebook.com/configcat), [LinkedIn](https://www.linkedin.com/company/configcat/), and [GitHub](https://github.com/configcat).