Skip to content

Instantly share code, notes, and snippets.

@chrismsimpson
Created October 5, 2019 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismsimpson/eb4a1e49067d4332f0631eed6a64d4e4 to your computer and use it in GitHub Desktop.
Save chrismsimpson/eb4a1e49067d4332f0631eed6a64d4e4 to your computer and use it in GitHub Desktop.
Environment extensions for Swift
import Foundation
public enum Environment: String {
// A plist should exist for each of the environments
// below. For example `case production = "Prod"` will
// have a corresponding `Prod.plist`.
case production
case staging
case development
// Below represents a key found in each/every plist
// file mentioned above
public enum Key: String {
case baseUrl = "BASE_URL"
case socialToken = "SOCIAL_TOKEN"
}
fileprivate class EnvBundleClass { }
private static var bundle: Bundle? = {
return Bundle(for: EnvBundleClass.self)
}()
public static var versionNumber: String? {
guard let version = bundle?.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String else {
return nil
}
return version
}
public static var buildNumber: String? {
guard let build = bundle?.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String else {
return nil
}
return build
}
public static var current: Environment = {
var raw: String?
if let currentConfig = bundle?.object(forInfoDictionaryKey: "Config") as? String {
raw = currentConfig
.replacingOccurrences(of: "Debug", with: "")
.replacingOccurrences(of: "Release", with: "")
.replacingOccurrences(of: "-", with: "")
}
if let raw = raw, let environment = Environment(rawValue: raw) {
return environment
}
return .production
}()
public static var plistPath: String? {
return Environment.bundle?.path(forResource: current.rawValue, ofType: "plist")
}
public static var plist: Dictionary<String, Any>? = {
guard let plistPath = plistPath else {
return nil
}
return NSDictionary(contentsOfFile: plistPath) as? Dictionary<String, Any>
}()
// MARK: - Convenience
public static func value<T>(for key: Environment.Key) -> T? {
return plist?[key.rawValue] as? T
}
public static func int(for key: Environment.Key) -> Int? {
return plist?[key.rawValue] as? Int
}
public static func string(for key: Environment.Key) -> String? {
return plist?[key.rawValue] as? String
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment