Skip to content

Instantly share code, notes, and snippets.

@LennyN95
Last active March 20, 2021 04:06
Show Gist options
  • Save LennyN95/cf52f0291514c1f584c1e2034145a5c0 to your computer and use it in GitHub Desktop.
Save LennyN95/cf52f0291514c1f584c1e2034145a5c0 to your computer and use it in GitHub Desktop.
A preset value wrapper that allows for modifications but maintains specific user modifications over the preset value.
//
// preset.swift
//
// Created by Leonard Nürnberg on 10.10.20.
// Copyright © 2020 Leonard Nürnberg. All rights reserved.
//
struct Preset<Value> {
private(set) var presetValue: Value
private var definedValue: Value?
/**
Initialize a new preset with a preset value, that will be used as value unless an explicit value has been set.
The preset value can be changed at any time and will reflect that changes, but only as long as the value has not altered directly.
This leads to a better user experience, because you can present dynamic preset values but as soon as the user makes a final decision and changes teh value, it will be consistent.
~~~
@State private var myPreset<String> = .init("default text A")
// change the preset for any reason
myPreset.preset("default text B")
// use the preset as binding
// the text will change accordingly from "default text A" to "default text B" as long as the user has not already changed the value.
TextField("demo", text: $myPreset.value)
~~~
- Parameters:
- preset: The initial preset value. This value can be altered using the preset() function.
*/
@inlinable init(_ preset: Value) {
presetValue = preset
}
/// access the wrapped value. This will be the preset value unless a value has been set once. From then on the explicitly set value will be returned instead of the preset.
/// when using the preset as a binding always use the wrapped value as the binding.
var value: Value {
get {
definedValue == nil ? presetValue : definedValue!
}
set {
definedValue = newValue
}
}
/// indicates whether a user defined value already exists or if the preset value is used and thus can be changed
var isPresetSetable: Bool {
definedValue == nil
}
/// set a new preset value that will be used as value unless an explicit value is set.
/// - Parameter value: The new preset value
mutating func preset(_ value: Value) {
presetValue = value
}
/// the reset function unsets the explicitly set value to fallback to the preset value.
mutating func reset() {
definedValue = nil
}
}
extension Preset: Equatable where Value: Equatable {
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.value == rhs.value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment