Created
August 29, 2018 16:43
-
-
Save AlexanderBollbach/d226e7f6fc50ae6807f20f07e9eaa2b9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| class Settings: Equatable { | |
| private var lastCommit: [SettingGroup] = initialSearchSettings() | |
| init(initialSettings: [SettingGroup]) { | |
| lastCommit = initialSettings | |
| resetToLastCommit() | |
| } | |
| func resetToLastCommit() { | |
| reset(to: lastCommit) | |
| } | |
| func commit() { | |
| lastCommit = groups | |
| } | |
| var groups: [SettingGroup] = [] { | |
| didSet { settingsUpdated() } | |
| } | |
| static func == (lhs: Settings, rhs: Settings) -> Bool { | |
| return lhs.groups == rhs.groups | |
| } | |
| init(groups: [SettingGroup]) { | |
| self.groups = groups | |
| } | |
| var settingsUpdated: () -> Void = {} | |
| func update(id: String, value: Setting.Value) { | |
| groups = groups.map { group in | |
| var newGroup = group | |
| newGroup.update(id: id, value: value) | |
| return newGroup | |
| } | |
| } | |
| func getValue<T>(forId id: String) throws -> T { | |
| for group in groups { | |
| if let value = group.getValue(forId: id) { | |
| switch value { | |
| case .enumeration(let state): | |
| if let result = state.current as? T { | |
| return result | |
| } else { | |
| throw SettingsError.noValueForId | |
| } | |
| case .toggle(let value): | |
| if let result = value as? T { | |
| return result | |
| } else { | |
| throw SettingsError.noValueForId | |
| } | |
| } | |
| } | |
| } | |
| throw SettingsError.noValueForId | |
| } | |
| // if one or more filters isActive == true than the filter groups are applied | |
| // make this smarter. perhaps it knows if its deviated from the initial state. | |
| func isApplied() -> Bool { | |
| return false | |
| // return filters(matching: { $0.isActive }).count > 0 | |
| } | |
| private func filters(matching predicate: (Setting) -> Bool) -> [Setting] { | |
| return (groups.compactMap { $0.settings }).joined().filter { predicate($0) } | |
| } | |
| func reset(to groups: [SettingGroup]) { | |
| self.groups = groups | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment