Swift: Simple Feature Flags

anoop m
2 min readNov 7, 2020

--

During these days where we thrive for Continuous integration, it is really critical that we constantly merge branches into the dev pool, and while doing that ,we must make sure features are not broken. Sometimes there can arise some scenarios that …a part of feature need to be released along with an existing part or there can be a scenario that a certain features are enabled only for testing (A/B testing or etc). We cant have separate branches for each particular case, as it will become non maintainable. So there comes the feature flags. There are multiple ways to implement it, here I am showing a simple way defining flags compile time using the power of enums.

Step1 : Define Environments

Better to map the environment with build configs

enum Environment {
case dev
case qa
case prod
}

Step2: Define FeatureTypes, with availability flags

enum FeatureType {
case feature1
case feature2

func isFeatureEnabledFor(environment: Environment) -> Bool {
switch environment {
case .dev:
switch self {
case .feature1:
return true
case .feature2:
return true
}
case .qa:
switch self {
case .feature1:
return true
case .feature2:
return false
}
case .prod:
switch self {
case .feature1:
return false
case .feature2:
return true
}
}
}
}

Here we define a FeatureType enum with the types of features to be toggled ON/ OFF . Then we will have a nested switch case which will return the respective flag for respective feature in the respective environment.

Usage

class MyClass {

let currentEnvironment = Environment.dev
func check() {
if(FeatureType.feature1.isFeatureEnabledFor(environment: currentEnvironment)) {
// Do something
} else {
// Use existing flow
}
if(FeatureType.feature2.isFeatureEnabledFor(environment: currentEnvironment)) {
// Do something else
} else {
// Use existing flow
}
}

}

Easy to use if you have controlled list of features.

--

--

No responses yet