From a6e86eddccb57bc34fa417cedc5900b8c8b89cc8 Mon Sep 17 00:00:00 2001 From: Kevin Mullins Date: Thu, 18 Jan 2024 06:31:10 -0600 Subject: [PATCH] MutableValue Added MutableValue property wrapper that creates a property that can be mutated in a SwiftUI view without kicking off a state change. --- .../SwiftUIKit/Properties/MutableValue.swift | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Sources/SwiftUIKit/Properties/MutableValue.swift diff --git a/Sources/SwiftUIKit/Properties/MutableValue.swift b/Sources/SwiftUIKit/Properties/MutableValue.swift new file mode 100644 index 0000000..505ea6e --- /dev/null +++ b/Sources/SwiftUIKit/Properties/MutableValue.swift @@ -0,0 +1,59 @@ +// +// Mutable.swift +// Escape from Mystic Manor +// +// Created by Kevin Mullins on 11/16/21. +// + +import Foundation +import SwiftUI + +/// Provides storage for my wrapped value +class ValueStorage { + + /// The value being stored + var storedValue:T? = nil + +} + +/// Creates a property that can be mutated in a SwiftUI view without kicking off a state change. +@propertyWrapper struct MutableValue { + /// Provides storage for the mutating value + private let storage:ValueStorage = ValueStorage() + private let name:String + + /// The value being wrapped. + var wrappedValue:T { + get { + if name != "" { + print("Fetching \(name): \(storage.storedValue!)") + } + return storage.storedValue! + } + nonmutating set { + storage.storedValue = newValue + if name != "" { + print("Setting \(name): \(storage.storedValue!)") + } + } + } + + // The value can be bound to SwiftUI + var projectedValue: Binding { + Binding( + get: { wrappedValue }, + set: { wrappedValue = $0 } + ) + } + + // Initializers + /// Initializes the mutating value. + /// - Parameter wrappedValue: The initial value for the property. + init(wrappedValue:T, name:String = "") { + self.storage.storedValue = wrappedValue + self.name = name + if name != "" { + print("Initializing \(name): \(wrappedValue)") + } + } +}