Last active
July 1, 2019 15:24
-
-
Save alexanderjrobinson/10564669ef8ebd528a6d7039da724402 to your computer and use it in GitHub Desktop.
Example of the Environment single for dependency injection and build configuration variants
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// Constant for configuration name from custom property in the Info.plist file | |
fileprivate let ConfigurationNameKey = "build.config" | |
// Singleton Instance used globally for shared resources and configuration | |
var ENV = Environment() | |
public struct Environment { | |
public enum Configuration: String { | |
case beta | |
case production | |
} | |
public private(set) var date: () -> Date = Date.init | |
public private(set) var configuration: Environment.Configuration = loadEnv() | |
} | |
extension Environment { | |
private static func loadEnv() -> Environment.Configuration { | |
guard let rawValue = Bundle.main.object(forInfoDictionaryKey: ConfigurationNameKey) | |
as? String else { return .production } | |
return Environment.Configuration(rawValue: rawValue) ?? .production | |
} | |
} | |
extension Environment.Configuration { | |
public var baseURL: URL { | |
switch self { | |
case .beta: return URL(string: "https://dev.example.com/")! | |
case .production: return URL(string: "https://example.com/")! | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment