Created
March 27, 2019 02:44
-
-
Save mlaster/6ec5ab0e5f82668f1f2b8cd8b85b2d18 to your computer and use it in GitHub Desktop.
Flattened hierarchical config
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
private protocol MutableConfigProtocol: ConfigProtocol { | |
var key1: String { get set } | |
var key2: Int { get set } | |
} | |
private protocol ConfigLayerProtocol { | |
var key1: String? { get } | |
var key2: Int? { get } | |
} | |
private struct FallbackConfig: MutableConfigProtocol { | |
var key1 = "" | |
var key2 = 0 | |
} | |
private struct ConfigLayer: ConfigLayerProtocol { | |
var key1: String? | |
var key2: Int? | |
} | |
private struct Config: ConfigProtocol { | |
public let key1: String | |
public let key2: Int | |
} | |
private func ||(lhs: MutableConfigProtocol, rhs: ConfigLayerProtocol) -> MutableConfigProtocol { | |
var merged = lhs | |
if let value = rhs.key1 { merged.key1 = value } | |
if let value = rhs.key2 { merged.key2 = value } | |
return merged | |
} | |
public protocol ConfigProtocol { | |
var key1: String { get } | |
var key2: Int { get } | |
} | |
public class ConfigCoordinator { | |
public static var config: ConfigProtocol { | |
let base = FallbackConfig() | |
var serverConfig = ConfigLayer() | |
serverConfig.key1 = "fromServer" | |
var userDefaultsConfig = ConfigLayer() | |
userDefaultsConfig.key2 = 23 | |
return base || serverConfig || userDefaultsConfig | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment