Created
April 22, 2022 08:09
-
-
Save TerjeLon/9864d24ae30f3e8375f11edaaa69402b to your computer and use it in GitHub Desktop.
Property wrapper for changing published values when in SwiftUI Preview mode
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 | |
import Combine | |
@propertyWrapper | |
public class PreviewPublisher<Value> { | |
let isPreview = ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" | |
private var defaultValue: Value | |
private var previewValue: Value | |
private let innerSubject = PassthroughSubject<Value, Never>() | |
public var wrappedValue: Value { | |
get { | |
return isPreview ? previewValue : defaultValue | |
} | |
set { | |
if isPreview { | |
previewValue = newValue | |
} else { | |
defaultValue = newValue | |
} | |
innerSubject.send(isPreview ? previewValue : defaultValue) | |
} | |
} | |
private var asPublisher: AnyPublisher<Value, Never> { | |
self.innerSubject.eraseToAnyPublisher() | |
} | |
public init(wrappedValue defaultValue: Value, _ previewValue: Value) { | |
self.defaultValue = defaultValue | |
self.previewValue = previewValue | |
} | |
public init(initialValue defaultValue: Value, _ previewValue: Value) { | |
self.defaultValue = defaultValue | |
self.previewValue = previewValue | |
} | |
} | |
extension PreviewPublisher: Publisher { | |
public typealias Output = Value | |
public typealias Failure = Never | |
public func receive<S>(subscriber: S) where S : Subscriber, Never == S.Failure, Value == S.Input { | |
self.asPublisher.receive(subscriber: subscriber) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment